(function ($) {
    var transferButton = false,
        errorFlag = false,
        hasRobot = false,
        maxHisMessageId = '',
        guessYouWantAskArr = [],
        guessYouWantAskPageMax = 0,
        guessYouWantAskPageLimit = 5,
        guessYouWantAskPagePage = 0,
        robotVersion = "",
        robotId = '',
        contentMaxHeight = 0,
        visitLoginCheck = false,
        transferNoticeShowDialog = true,
        isWework = false,
        feedbackTips = i18n.robot.feedbackTips,
        likeButton = false,
        likeButtonName = i18n.robot.likeButtonName,
        stepButton = false,
        stepButtonName = i18n.robot.stepButtonName,
        afterStepToShowTransferButton = false,
        transferName = i18n.robot.transferName,
        transferTips = i18n.robot.transferTips,
        isHiddenTransferHtml = true,
        allowRateForClientCloseSession = true,
        sessionRound = 3,
        orderHrefType = 0, //  orderHrefType 0: 为IFRAME方式打开   1: LOCATION方式打开
        roundTime = 0,
        fileUrl = '',
        mobileVerify = false,
        ordersPageSize = 3,
        lastReplyIsDefault = false,
        ZTEDPGSSOUser = "",
        timerNum = 0,
        UCSSSOAccount = "",
        showCityButton = false,
        showRateButton = false,
        showNavBarButton = false,
        robotTools = false,
        compressionImage = false,
        questionRecommendationStayTime = 3000,
        mobileVerifyPath = '', //手机验证隐私协议路径

        slimContent = false,
        robotListView = false, //机器人的显示方式
        multipleHistories = false, //历史是否展示为你查看的问题如下
        robotCodeReject = 0, //知识库连续搜索不到的问题ssss
        robotLikeReject = 0, //知识库连续点击没用
        showTimeObj = {
            quickCard: false,
            guessCard: false,
            quickEntry: false
        },
        htmlForZTEStep = '<div id="sry" class="popdis" style="display: block;">' +
        '<div>' +
        '   <img src="images/dis.png" alt="对不起" width="120" height="100" style="float:left;">' +
        '    <p class="sorrytext">对不起，没能解决您的问题。<br>你的反馈会使我们下次做的更好！</p>' +
        '  </div>' +
        '  <div class="step-reason" style="clear: both;">' +
        '    <button class="but01 but" id="but01" type="button">方法行不通</button>' +
        '    <button class="but02 but" id="but02" type="button">答非所问</button>' +
        '    <button class="but03 but" id="but03" type="button">内容看不懂</button>' +
        '    <button class="but04 but" id="but04" type="button">内容太啰嗦</button>' +
        '  </div>' +
        '  <div>' +
        '    <p class="texttitle">有话要说（选填）</p>' +
        '    <textarea id="adviceInPopdis" placeholder="请输入任何想发表的意见或建议，我们一定会真诚对待~"></textarea>' +
        '  </div>' +
        '  <div style="text-align: center">' +
        '      <button class="cancel" type="button">取消</button>' +
        '      <button class="submit" type="submit">提交</button>' +
        '  </div>' +
        '  <button class="close" id="disclose"></button>' +
        '  <input type="hidden" id="queryInPopdis" value="">' +
        '  <input type="hidden" id="answerInPopdis" value="">' +
        '  <input type="hidden" id="accountInPopdis" value="">' +
        '</div>',
        htmlForYANXIStep = '',
        sessionRoundTips = i18n.robot.sessionRoundTips;
    if (typeof $config === 'undefined') {
        $config = {
            agent: true
        };
    }

    var ORDER_MESSAGE = i18n.robot.orderMessage;
    var robotEngineConfig;

    function getLikeAndStepButtonHtml(messageId, robotId, htmlData) {
        var html = "";
        if (likeButton || stepButton) {
            html += '<div class="rate-message likes" data-feedback="true">' +
                '<div>' +
                '<p>' + feedbackTips + '</p>';
            if (stepButton) {
                html += '<div class="step" data-id="' + messageId + '" data-robotId="' + robotId + '" ' + htmlData + '><i></i>' + stepButtonName + '</div>';
            }
            if (likeButton) {
                html += '<div class="like" data-id="' + messageId + '" data-robotId="' + robotId + '" ' + htmlData + '><i></i>' + likeButtonName + '</div>';
            }
            html += '</div></div>';
        }
        return html;
    }

    function sendMsgWithSearchKeyBase(msg, searchKey, extra) {
        if (msg) {
            if ($config.mobile) {
                sendMsgWithSearchKey(msg, searchKey, extra);
            } else {
                sendCommentWithSearchKey(msg, searchKey, extra);
            }
        }
    }

    function getNoticeForTransferMessage(transfer) {
        return '<dl class="message clearfix message-notice" data-click="true" data-transfer=\'' + (transfer || '') + '\'>' +
            '<div class="transfer-notices">' + transferTips + '</div>' +
            '</dl>';
    }

    function getNoticeForTransferMessageWhenRejectRecog() {
        return '<dl class="message clearfix message-notice session-round" data-click="true">' +
            '<div class="transfer-notices">' + wrapZRGForTips(sessionRoundTips) + '</div>' +
            '</dl>';
    }

    function getTransferClickHtml() {
        return '<a class="transfer-notice" data-click="true">' + transferName + '</a>';
    }

    function hiddenTransferHtml() {
        if (isHiddenTransferHtml) {
            $('.transfer-notice').removeClass('transfer-notice')
            // $(".message-notice:not(.session-round)").hide();
        }
    }

    function wrapZRGForTips(tips) {
        var zrgRegExp = new RegExp(/\[ZRG](.*?)\[\/ZRG]/g);
        if (zrgRegExp.test(tips)) {
            tips = tips.replaceAll(zrgRegExp, '<span class="transfer-notice">$1</span>');
        }
        return tips;
    }

    function getTranseferButtonHtml(flag) {
        if (!flag && transferButton) {
            return '<hr>' +
                '<div class="transfer-message">' +
                '<p>转人工</p>' +
                '</div>'
        } else {
            return "";
        }
    }

    function getImageHtml(src, alt) {
        return '<image src="' + src + '" alt="' + alt + '" style="max-width: 300px; max-height: 300px;"/>';
    }

    function sendFeedback(data, callback) {
        $.post("client/jsonHttpRemote.do", {
            requestType: "feedback",
            sessionId: $config.sessionId,
            data: data
        }, callback);
    }

    function stepHtml(dom, preCallback, callback) {
        if ($("#sry")[0]) $("#sry").remove();
        $("body").append(dom);
        preCallback();
        $(".popdis .but").off().click(function () {
            if ($(this).hasClass("active")) {
                $(this).removeClass("active");
            } else {
                $(this).addClass("active");
            }
        });
        $(".popdis .submit").off().click(function () {
            var reason = '';
            $.each($(".step-reason .active"), function (i, actives) {
                reason += $(actives).text() + ";";
            });
            var advice = $("#adviceInPopdis").val();
            isUseful = "true";
            callback({
                "reason": reason,
                "advice": advice,
            });
            $("#sry").remove();

        });
        $(".popdis .cancel").off().click(function () {
            $("#sry").remove();
        });
    }

    function showMessageForRobot(messageStr) {
        if (messageStr) {
            if ($config.mobile) {
                var container = getDisplayMessage(ROBOT_ID.TEXTBOT, Constants.robot.name, messageStr, '')
                if (container) {
                    attachImgEvent(container, 1);
                }
            } else {
                var displayMessage = $F.getDisplayMessage(ROBOT_ID.TEXTBOT, Constants.robot.name, messageStr, null, null, '');
                $F.appendTextToDiv("clientResponseDiv", displayMessage);
            }
        }
    }

    function feedbackFunc(feedType, $thisDom, userId) {
        var data = "";
        switch (userId) {
            case ROBOT_ID.ZTEROBOT:
                var account = $thisDom.data("account"),
                    query = $thisDom.data("query"),
                    answer = $thisDom.data("answer"),
                    reason = $thisDom.data("reason"),
                    advice = $thisDom.data("advice");
                var isUseful = "false";
                if (feedType == 1) {
                    isUseful = "true";
                    data = JSON.stringify({
                        "query": query,
                        "answer": answer,
                        "isUseful": isUseful,
                        "reason": reason,
                        "advice": advice,
                        "account": account
                    });
                    sendFeedback(data);
                } else {
                    stepHtml(htmlForZTEStep, function () {
                        $("#queryInPopdis").val(query);
                        $("#answerInPopdis").val(answer);
                        $("#accountInPopdis").val(account);
                    }, function (rate) {
                        var data = JSON.stringify({
                            "query": $("#queryInPopdis").val(),
                            "answer": $("#answerInPopdis").val(),
                            "isUseful": isUseful,
                            "reason": rate.reason,
                            "advice": rate.advice,
                            "account": $("#accountInPopdis").val()
                        });
                        sendFeedback(data);
                    });
                }

                break;
            case ROBOT_ID.EMOTIBOT: //竹间机器人的反馈信息
                var uuid = $thisDom.data("uuid");
                if (feedType == 1) {
                    data = JSON.stringify({
                        "helpful": "helpful",
                        "content": "",
                        "uuid": uuid
                    });
                } else {
                    data = JSON.stringify({
                        "helpful": "unhelpful",
                        "content": "",
                        "uuid": uuid
                    });
                    //点踩的时候显示转人工提示信息
                    $thisDom.parent().html("<hr>" + getNoticeForTransferMessage());
                }
                sendFeedback(data);
                break;
            case ROBOT_ID.SINOROBOT: //竹间机器人的反馈信息
                if (feedType == 1) {
                    data = JSON.stringify({
                        "solveStatus": "1",
                        "serviceLogId": $thisDom.data("servicelogid")
                    });
                } else {
                    data = JSON.stringify({
                        "solveStatus": "0",
                        "serviceLogId": $thisDom.data("servicelogid")
                    });
                    //点踩的时候显示转人工提示信息
                    $thisDom.parent().html("<hr>" + getNoticeForTransferMessage());
                }
                sendFeedback(data);
                break;
            case ROBOT_ID.SOBOT: //智齿机器人
                var docname = $thisDom.data("docname") || "",
                    msgid = $thisDom.data("msgid") || "",
                    uid = $thisDom.data("uid") || "",
                    cid = $thisDom.data("cid") || "",
                    docid = $thisDom.data("docid") || "";
                if (feedType == 1) {
                    data = JSON.stringify({
                        "status": "1",
                        "docname": docname,
                        "msgid": msgid,
                        "uid": uid,
                        "cid": cid,
                        "docid": docid
                    });
                } else {
                    data = JSON.stringify({
                        "status": "-1",
                        "docname": docname,
                        "msgid": msgid,
                        "uid": uid,
                        "cid": cid,
                        "docid": docid
                    });
                }
                sendFeedback(data);
                break;
            case ROBOT_ID.XIAOIBOT:
                var data = $thisDom.data(),
                    id = data.id,
                    type = data.post,
                    revoke = data.revoke;
                data = JSON.stringify({
                    "messageId": id,
                    "revoke": revoke,
                    "type": type
                });
                sendFeedback(data);
                break;
            case ROBOT_ID.YANXIBOT:
                var data = $thisDom.data(),
                    evaluateType = $thisDom.data().evaluatetype,
                    answerMessageId = $thisDom.data().answermessageid;
                if (feedType == 1) {
                    data = JSON.stringify({
                        "answerMessageId": answerMessageId,
                        "evaluateType": evaluateType,
                        "evaluateContent": '有用'
                    });
                    sendFeedback(data);
                } else {
                    if (htmlForYANXIStep) {
                        stepHtml(htmlForYANXIStep, function () {}, function (rate) {
                            data = JSON.stringify({
                                "answerMessageId": answerMessageId,
                                "evaluateType": 0,
                                "evaluateContent": '没用'
                            });
                            sendFeedback(data);
                        });
                    } else {
                        data = JSON.stringify({
                            "answerMessageId": answerMessageId,
                            "evaluateType": 0,
                            "evaluateContent": '没用'
                        });
                        sendFeedback(data);
                    }
                }
                break;
            case ROBOT_ID.TEXTBOT:
                var data = $thisDom.data(),
                    messageid = $thisDom.data().messageid;
                if (feedType == 1) {
                    data = JSON.stringify({
                        "key": robotEngineConfig.property.key,
                        "bind_code": robotEngineConfig.property.bindCode,
                        "msg_id": messageid,
                        "chat_user_id": $config.client.clientId,
                        "is_solved": true,
                    });
                    robotLikeReject = 0;
                } else {
                    data = JSON.stringify({
                        "key": robotEngineConfig.property.key,
                        "bind_code": robotEngineConfig.property.bindCode,
                        "msg_id": messageid,
                        "chat_user_id": $config.client.clientId,
                        "is_solved": false,
                    });
                    robotLikeReject++
                }

                sendFeedback(data, function (data) {
                    if (data.status == 'success') {
                        var value = data.value;
                        if (value.success) {
                            if (feedType == 1) {
                                showMessageForRobot(robotEngineConfig.feedbackLike);
                            } else {
                                if (robotLikeReject >= (robotEngineConfig.clickStep || 2)) {
                                    showMessageForRobot(robotEngineConfig.stepClickTips);
                                    robotLikeReject = 0;
                                } else {
                                    showMessageForRobot(robotEngineConfig.feedbackStep);
                                }
                            }
                        } else {
                            showMessageForRobot(robotEngineConfig.feedbackFail)
                        }

                    };
                });
                break;
            case ROBOT_ID.GUANGDABOT:
                var data = $thisDom.data(),
                    id = data.id,
                    type = data.useFul;
                if ($thisDom.hasClass('like')) {
                    data = JSON.stringify({
                        "useful": true,
                        "id": id
                    });
                    robotLikeReject = 0;
                } else {
                    data = JSON.stringify({
                        "useful": false,
                        "id": id
                    });
                    robotLikeReject++;
                }
                sendFeedback(data);
                if (robotLikeReject > 1) {
                    domToDialog(getNoticeForTransferMessage());
                }
                break;
            case ROBOT_ID.RLTEXTBOT:
                var data = $thisDom.data(),
                    oriquestion = data.oriquestion,
                    confidence = data.confidence,
                    answer = data.answer || '',
                    channel = data.channel || '',
                    distributechannel = data.distributechannel,
                    question = data.question,
                    data = {
                        'ori_question': oriquestion,
                        'confidence': confidence,
                        'answer': answer,
                        'distribute_channel': distributechannel,
                        'channel': channel,
                        'question': question
                    }
                if ($thisDom.hasClass('like')) {
                    data.is_useful = true;
                } else {
                    data.is_useful = false;
                }
                sendFeedback(JSON.stringify(data));
                break
            case ROBOT_ID.IWENCAIBOT:
                var data = $thisDom.data(),
                    topic = data.topic,
                    questionId = data.questionid,
                    data = {
                        'topic_name': topic,
                        'question_id': questionId
                    }
                if ($thisDom.hasClass('like')) {
                    data.id = 'click_use';
                } else {
                    data.id = 'click_noUse';
                }
                sendFeedback(JSON.stringify(data));
                break
        }
    };

    function getGuessYouAsk(self) {
        console.log("获取猜你想问的dom");
        var html = '<h4>' + i18n.page.guessYouWantAsk + '</h4>'; //猜你想问的标题
        var max = (guessYouWantAskPagePage + 1) * guessYouWantAskPageLimit > guessYouWantAskPageMax ? guessYouWantAskPageMax : (guessYouWantAskPagePage + 1) * guessYouWantAskPageLimit;
        for (var i = guessYouWantAskPagePage * guessYouWantAskPageLimit; i < max; i++) {
            html += '<div class="send-message" data-message="' + guessYouWantAskArr[i].value + '">' + guessYouWantAskArr[i].text + '</div>';
        }
        guessYouWantAskPagePage++;
        if (max == guessYouWantAskPageMax) {
            guessYouWantAskPagePage = 0;
        }
        if (guessYouWantAskPageMax > guessYouWantAskPageLimit)
            html += '<div class="change-batch">' + i18n.page.changeABatch + '</div>'; //换一批按钮
        return html;
    }

    /**
     * 将dom展示到对话框
     * @param preview 展示的内容
     */
    function domToDialog(preview) {
        appendTextToStandardDiv("clientResponseDiv", '<div class="custom_service clear_box"  onload="setViewportScrollTop($(this).height());"  data-id="">' +
            '<div>' +
            '<img class="avatar" src="' + (Constants.robot.iconUrl) + '" alt="' + Constants.robot.iconAlt + '" />' +
            '</div>' +
            '<div class="contentBox">' +
            '<p class="nickname">' + (Constants.agent.id ? Constants.agent.name : Constants.robot.name) + '</p>' +
            '<div class="content">' + preview + '</div>' +
            '</div>' +
            '</div>', 1);
    };

    $(document).on("click", ".transfer-message", function () {
        console.log("转人工操作");
        $ROBOT.transferChat($config.queueId, "");
    }).on("click", ".message-title", function () {
        var id = $(this).attr("data-id"),
            title = $(this).attr("data-title"),
            preview = $(this).next().html(),
            messageId = $(this).data('messageid'),
            url = $(this).data("url"),
            question = $(this).attr("data-question"),
            disable = $(this).parent().data("disable") || $(this).data("disable") || '',
            once = $(this).data("once") || '';
        if (url) {
            if ($config.mobile) {
                showNewBottomPage(url);
            } else {
                window.open(url);
            }
            return;
        }
        if (disable) return;
        else {
            if (once) $(this).data("disable", 1).addClass("btn-disable")
                .siblings().data("disable", 1).addClass("btn-disable");
            preview = wrapURL(preview);
            var dom = '';
            if (ROBOT_ID.YANXIBOT == robotId) {
                dom = 'data-evaluateType= "5" data-answerMessageId="' + messageId + '"';
            }
            if (ROBOT_ID.GUANGDABOT != robotId)
                preview += getLikeAndStepButtonHtml("", robotId, dom);
            if (!$config.mobile) {
                if (robotId !== ROBOT_ID.KMBOT) {
                    $F.appendTextToDiv($F.getDisplayMessage(robotId, Constants.client.clientFirstName, title, $F.parseDate(new Date()), Constants.client.iconUrl))
                    // $F.appendTextToDiv("clientResponseDiv", '<div class="message clearfix me">' +
                    //     '<div class="nowtime me-time">' +
                    //     '<span class="me-name">' + Constants.client.clientFirstName + '</span>' +
                    //     '</div>' +
                    //     '<div><img class="avatar" src="' + (Constants.client.iconUrl) + '" alt="' + Constants.client.iconAlt + '" /><i class="icon"></i></div>' +
                    //     '<div class="contentBox"><div class="content">' + title + '</div></div>' +
                    //     '</div>');
                }
                $F.appendTextToDiv("clientResponseDiv", '<div class="message clearfix lele">' +
                    '<div class="nowtime lele-time">' +
                    '<span class="me-name">' + (Constants.robot.name || '人工客服') + '</span>' +
                    '</div>' +
                    '<div><img class="avatar" src="' + (Constants.robot.iconUrl) + '" alt="' + Constants.robot.iconAlt + '" /><i class="icon"></i></div>' +
                    '<div class="contentBox"><div class="content">' + preview + '</div></div>' +
                    '</div>');
            } else {
                appendTextToStandardDiv("clientResponseDiv", '<div class="user clear_box"  onload="setViewportScrollTop($(this).height());">' +
                    '<div><img class="avatar" src="' + (Constants.client.iconUrl) + '" alt="' + Constants.client.iconAlt + '" /></div>' +
                    '<div class="contentBox">' +
                    '<p class="nickname">' + Constants.client.clientName +
                    '</p>' +
                    '<div class="content">' + title +
                    '</div>' +
                    '</div>' +
                    '</div>', 1);
                domToDialog(preview)
            }
        }
    }).on("click", ".relate_body_li", function () {
        var $this = $(this),
            msg = $this.text(),
            msg = $this.data("msg") || msg,
            search = $this.data("search") || '',
            extra = $this.data("extra") || '';
        sendMsgWithSearchKeyBase(msg, search, extra);
    }).on('click', '.tab-title', function () {
        var id = $(this).attr('data-id')
        $('span', $('.tabs')).removeClass('active')
        $(this).addClass('active')
        $('span', $('.tabContent')).css('display', 'none')
        $('span[data-id="' + id + '"]', $('.tabContent')).css('display', 'block').siblings().css('display', 'none')
    }).on("click", ".send-message", function () {
        var cmd = $(this).data("cmd"),
            extra = $(this).data("extra") || '',
            disable = $(this).data("disable") || '',
            once = $(this).data("once") || '';
        if (disable) return;
        else {
            if (once) $(this).data("disable", 1).addClass("btn-disable")
                .siblings().data("disable", 1).addClass("btn-disable");
            if (cmd) {
                if ("zrg" == cmd) {
                    $ROBOT.transferChat($config.queueId, "");
                }
            }
            var msg = $(this).data("message");
            var searchKey = $(this).data("key") ? $(this).data("key") + '' : '';
            if (searchKey.startWith('faqvote')) {
                $(".send-message", $(this).parent()).removeClass("send-message");
            }
            sendMsgWithSearchKeyBase(msg, searchKey, extra);
        }
    }).on("click", ".like", function () {
        var $rateMessage = $(this).parent().parent();
        var feedback = $rateMessage.data('feedback');
        if (feedback) {
            $rateMessage.data('feedback', false);
            var robotMessageId = $(this).data("id");
            var searchKey = $(this).data("search") || '';
            var msg = $(this).data("msg") || '';
            var extra = $(this).data("extra") || ''
            sendMsgWithSearchKeyBase(msg, searchKey, extra);
            $(this).addClass("active");
            console.log("对消息[" + robotMessageId + "]进行点赞处理")
            feedbackFunc(1, $(this), $(this).data("robotid"));
        }
    }).on("click", ".step", function () {
        var $rateMessage = $(this).parent().parent();
        var feedback = $rateMessage.data('feedback');
        if (feedback) {
            $rateMessage.data('feedback', false);
            var robotMessageId = $(this).data("botId"),
                searchKey = $(this).data("search") || '',
                msg = $(this).data("msg") || '',
                extra = $(this).data("extra") || '',
                reason = $(this).data("reason") || false;
            searchKey = searchKey.replace('{4}', '');
            $(this).addClass("active");
            console.log("对消息[" + robotMessageId + "]进行点踩处理");
            if (reason) { //显示不满意的原因
                var $stepExtend = $('.step-extend', $rateMessage);
                // reason = JSON.parse(reason);
                if ($config.mobile) {
                    layer.open({
                        content: $stepExtend.html(),
                        className: 'confirm-mobile',
                        btn: ['关闭'],
                        shadeClose: false,
                        yes: function (index) {
                            sendMsgWithSearchKeyBase(msg, searchKey, extra);
                            feedbackFunc(0, $(this), $(this).data("robotid"));
                            layer.close(index)
                        }
                    });
                } else {
                    $stepExtend.show();
                }
            } else {
                sendMsgWithSearchKeyBase(msg, searchKey, extra);
                feedbackFunc(0, $(this), $(this).data("robotid"));
                // if (afterStepToShowTransferButton) { // 如果配置了点击踩之后提示是否转人工的提示需要执行下面的代码
                //     if (!$config.mobile) {
                //         $F.appendTextToDiv("clientResponseDiv", getNoticeForTransferMessage());
                //     } else {
                //         appendTextToStandardDiv("clientResponseDiv", getNoticeForTransferMessage(), 1);
                //     }
                // }

            }
        }

    }).on("click", ".step-li", function () {
        var robotMessageId = $(this).data("botId"),
            searchKey = $(this).data("search") || '',
            msg = $(this).data("msg") || '',
            detail = (': ' + $(this).data("detail")) || '',
            extra = $(this).data("extra") || '';
        $(this).children('i').addClass("active");
        $(this).addClass('active').parent().parent().hide();
        layer.closeAll();
        console.log("未解决扩展，对消息[" + robotMessageId + "]进行点踩处理");
        sendMsgWithSearchKeyBase(msg + detail, searchKey, extra);
        feedbackFunc(0, $(this), $(this).data("robotid"));
    }).on("click", ".show-iframeUrl", function () {
        var url = $(this).data("url"),
            disable = $(this).data("disable") || '',
            once = $(this).data("once") || '';
        if (disable) return;
        else {
            if (once) $(this).data("disable", 1).addClass("btn-disable")
                .siblings().data("disable", 1).addClass("btn-disable");
            if ($config.mobile) {
                showNewBottomPage(url);
            } else {
                window.open(url);
            }
        }
    }).on("click", ".transfer-notice", function () {
        var $messageNotice = $(this).parent().parent();
        if ($messageNotice.data('click')) {
            $messageNotice.data('click', false);
            var transferInfo = $messageNotice.data("transfer") || '';
            console.log("点击转人工按钮转人工操作");
            if (visitLoginCheck && typeof loginWhenVisit == 'function') {
                loginWhenVisit(function () {
                    //显示对话框
                    if (transferNoticeShowDialog) {
                        $ROBOT.transferDialog("", function () {
                            $ROBOT.transferChat($config.queueId, transferInfo);
                        })
                    } else {
                        $ROBOT.transferChat($config.queueId, transferInfo);
                    }
                })
            } else {
                if ($ROBOT.isPocVersion()) {
                    $("#popDiv").show();
                } else {
                    if (transferNoticeShowDialog) {
                        $ROBOT.transferDialog("", function () {
                            $ROBOT.transferChat($config.queueId, transferInfo);
                        })
                    } else {
                        $ROBOT.transferChat($config.queueId, transferInfo);
                    }
                }
            }
        }
    }).on("click", ".robot-ques li", function (event) {
        event.stopPropagation();
        var text = $(this).text();
        console.log("select remond questions ：" + text);
        if ($config.mobile) {
            sendMsg(text);
        } else {
            sendComment(text);
        }
        $(".robot-ques").hide();
    }).on("click", ".message-card", function () {
        var url = $(this).data('url');
        if ($config.mobile) {
            showNewBottomPage(url);
        } else {
            window.open(url);
        }
    }).on("click", ".message-imgtext, .message-orders", function () {
        var url = $(this).data('url'),
            text = $(this).data('send'),
            key = $(this).data("key"),
            hassend = $(this).data("hassend"),
            from = $(this).data("from"),
            funca = $(this).data("funca"),
            funci = $(this).data("funci"),
            keyFrom = $(this).data('keyfrom') || "";

        if (!hassend) {
            if (text) {
                sendMsgWithSearchKeyBase(text, key, 'orders')
            }
            if (from == 'uniqlo') {
                $('[data-keyfrom="' + keyFrom + '"]').data("hassend", "1");
            }
        }

        if (url) {
            if ($config.mobile) {
                if (orderHrefType == 0) {
                    showNewBottomPage(url);
                } else {
                    location.href = url;
                }

            } else {
                window.open(url);
            }
        }
        try {
            if (isIOS) {
                if (funci) {
                    eval(funci);
                }
            } else {
                if (funca) {
                    eval(funca);
                }
            }
        } catch (e) {
            console.log("error run function :" + e);
        }
    }).on("click", ".orders-button", function () {
        var type = $(this).data("type"),
            parentData = $(this).parent(),
            messageOrders = parentData.parent().children('.message-orders'),
            page = parentData.data('page'),
            size = parentData.data('size');

        if (type == 'next') {
            if (0 < page + 1 && page + 1 < size) {
                parentData.data("page", ++page);
                $.each(messageOrders, function (i, orderDiv) {
                    var index = orderDiv.dataset["index"];
                    if (index == page) {
                        $(this).show();
                    } else {
                        $(this).hide();
                    }
                })
            }
        } else if (type == 'prev') {
            if (0 < page && page < size) {
                parentData.data("page", --page);
                $.each(messageOrders, function (i, orderDiv) {
                    var index = orderDiv.dataset["index"];
                    if (index == page) {
                        $(this).show();
                    } else {
                        $(this).hide();
                    }
                })
            }
        }
    }).on("click", ".card-buttonItem", function () {
        var active = $(this).toggleClass("active");
    }).on("click", ".card-btnSure", function () {
        var active = $(this).data("active");
        if (active == 'sure') {
            var robotCard = $(this).parents('.robot-card');
            var buttonItem = $('.card-buttonItem.active', robotCard);
            if (buttonItem.length > 0) {
                var arrSelect = [];
                $.each(buttonItem, function (i, item) {
                    arrSelect.push($(item).data('title'));
                })
                var selectStr = arrSelect.join(";");
                if ($config.mobile) {
                    sendMsgWithSearchKey(selectStr, "", "");
                } else {
                    sendCommentWithSearchKey(selectStr, "", "");
                }
            }
        }
    }).on("click", ".change-batch", function () {
        var html = getGuessYouAsk();
        $(this).parent().html(html);
    });


    /**
     * 去掉字符串中带有'CDATA'
     * @param str
     * @returns {*}
     */
    function wrapCDATA(str) {
        var reg = new RegExp(/<\!\[CDATA\[([\S\s].*)\]\]>/i);
        while (reg.test(str)) {
            str = str.replace(reg, '$1').replace('<![CDATA[]]>', '');
        }
        return str;
    }

    function addclick(i, msg) {
        if (i != 0) {
            if (!multipleHistories) {
                return '<a class="send-message" data-message="' + msg + '">' + '[' + i + '] ' + msg + '</a>';
            } else {
                return "<i>" + '[' + i + '] ' + msg + "</i>";
            }
        } else {
            if (!multipleHistories) {
                return '<a class="send-message" data-message="' + msg + '">' + msg + '</a>';
            } else {
                return "<i>" + msg + "</i>";
            }
        }

    };

    function getRalateHtml(i, title, question, href, preview) {
        var html = "";
        if (!multipleHistories) {
            html = '<div class="each-message">' +
                '<div class="message-title" data-url="' + href + '" data-title = "' + title + '" data-question = \'' + (title || question) + '\' >' +
                '<a data-url="' + href + '">' + (i + 1) + '. ' + (title || question) + '</a>' +
                '</div>';
            html += '<div class="message-preview" style="display: none">' + preview;
            if (href) {
                html += i18n.robot.showRalate.format('<a href="' + href + '" target="_blank">', '</a>');
            }
            html += '</div></div>';
        }
        return html;
    }

    var $ROBOT_MOBILE = {
        appendTextToDiv: function (divId, data) {
            var container = $("<div>").append(data);
            $("#" + divId).append(container);
            container.find("img:not(.thumb, .emot, .avatar, .tb-img, .ke-emoji)").each(function (i, img) {
                var imgObj = $(img);
                imgObj.css("cursor", "pointer").off("load").on("load", function () {
                    autoResizeImage(300, 300, this);
                    // setViewportScrollTop($("#clientResponseDiv").height());
                    var scrollHeight = 0 - this.height;
                    if (scrollHeight == 0) {
                        scrollHeight = -300;
                    }
                    if (hist == '1') {
                        setTimeout(function () {
                            setViewportScrollby(scrollHeight, 'img.load');
                        }, 500)
                    }
                }).on("click", function () {
                    showOriginImage(this);
                    // $COMM.showOriginImage(this);
                });
            });

            $('.lele .avatar', container).on('error', function () {
                $(this).attr('src', 'jsp/standard/theme/' + $config.theme + '/img/agent.jpg');
            });

            $('.me .avatar', container).on('error', function () {
                $(this).attr('src', 'jsp/standard/theme/' + $config.theme + '/img/client.jpg');
            });
            // setViewportScrollTop($("#clientResponseDiv").height());
            scrollBottom("$ROBOT_MOBILE.appendTextToDiv")
        },
        formatNotice: function (msg) {
            return "<p class=\"messageTips\"><em>" + msg + "</em></p>";
        },
        formatNoticeForTransfer: function (msg) {
            return '<p class="messageTips transfer-message-tips"><em>' + msg + '</em></p>';
        }
    }

    var postQuestion = function (msg) {
        doAjaxCall(ajaxURL, "requestType=send&data=" + getPostMessageSentInfoJSON(encodeURIComponent(msg)), null);
    };

    function robotLog(text, from) {
        if (from)
            from = 'robotLog -> ' + from
        if (!$config.agent) {
            if ($config.mobile) {
                if (typeof text == 'object')
                    console.log('from [%s]- %o', from, text);
                else
                    console.log('from [%s]- %s', from, text);
            } else {
                if (typeof text == 'object')
                    $F.log('from [' + from + ']-' + JSON.stringify(text));
                else
                    $F.log('from [' + from + ']-' + text);
            }
        } else {
            console.log('from [' + from + ']-' + text);
        }

    }

    function handleKMBOTData(text, flag) {
        var html = '';
        var question = text.question;
        var srs = text.srs;
        if (srs && srs.length > 0) {
            var href = 'javascript:;';
            $.each(srs, function (i, item) {
                if (item.ra)
                    href = $ROBOT.wanUrl() + item.ra.path;
                else
                    href = null;
                html += getRalateHtml(i, item.title, item.question, href, item.preview);
            });
        } else {
            html += text.message;
        }
        return html;
    }

    /**
     * 光大机器人处理
     * @param text
     * @param flag
     */
    function handleGUANGDABOTData(text, flag) {
        if (text.code == 200) {
            var html = '';
            var data = text.data;
            switch (text.data.length) {
                case 0:
                    if (robotCodeReject >= 1) {
                        robotCodeReject = 0;
                        html = getNoticeForTransferMessage();
                    } else {
                        robotCodeReject = robotCodeReject + 1;
                        html = i18n.robot.noAnswer;
                    }
                    break;
                case 1:
                    if (data[0].content == '<p>转人工</p>') {
                        html = getNoticeForTransferMessageWhenRejectRecog();
                    } else {
                        $.each(data, function (i, item) {
                            html += item.title + '<br>' + item.content + getLikeAndStepButtonHtml(item.id, robotId, '');
                        });
                    }
                    robotCodeReject = 0;
                    break;
                case 2:
                    html = '<div class="content-title">您搜索的问题如下：</div>';
                    $.each(data, function (i, item) {
                        if (robotListView) {
                            html += '<div class="send-message" data-message="' + item.title + '">' + item.title + '</div>';
                        } else {
                            if (item.content === '<p>转人工</p>') {
                                html += getRalateHtml(i, item.title, item.title, null, getNoticeForTransferMessageWhenRejectRecog())
                            } else {
                                html += getRalateHtml(i, item.title, item.title, null, item.content + getLikeAndStepButtonHtml(item.id, robotId, ''))
                            }
                        }
                    });
                    robotCodeReject = 0;
                    break;
                case 3:
                    html = '<div class="content-title">您搜索的问题如下：</div>';
                    $.each(data, function (i, item) {
                        if (robotListView) {
                            html += '<div class="send-message" data-message="' + item.title + '">' + item.title + '</div>';
                        } else {
                            if (item.content === '<p>转人工</p>') {
                                html += getRalateHtml(i, item.title, item.title, null, getNoticeForTransferMessageWhenRejectRecog())
                            } else {
                                html += getRalateHtml(i, item.title, item.title, null, item.content + getLikeAndStepButtonHtml(item.id, robotId, ''))
                            }
                        }
                    });
                    robotCodeReject = 0;
                    break;
                case 4:
                    html = '<div class="content-title">您搜索的问题如下：</div>';
                    $.each(data, function (i, item) {
                        if (robotListView) {
                            html += '<div class="send-message" data-message="' + item.title + '">' + item.title + '</div>';
                        } else {
                            if (item.content === '<p>转人工</p>') {
                                html += getRalateHtml(i, item.title, item.title, null, getNoticeForTransferMessageWhenRejectRecog())
                            } else {
                                html += getRalateHtml(i, item.title, item.title, null, item.content + getLikeAndStepButtonHtml(item.id, robotId, ''))
                            }
                        }
                    });
                    robotCodeReject = 0;
                    break;
                default:
                    html = '<div>您可以描述的更清楚些吗？</div>';
                    robotCodeReject = 0;
                    break;
            }
        } else if (text.code == 1) {
            if (robotCodeReject >= 1) {
                robotCodeReject = 0;
                html = getNoticeForTransferMessage();
            } else {
                robotCodeReject = robotCodeReject + 1;
                html = i18n.robot.noAnswer
            }
        } else {
            html = i18n.robot.noAnswer;
        }
        // 清除计数
        if (flag) {
            robotCodeReject = 0;
            robotLikeReject = 0;
        }
        return html;
    }

    function handleXiaoDuobotData(text, flag) {
        var show = false,
            transferFlag = false;
        var html = '';
        if (typeof text == 'string') {
            text = JSON.parse(text);
        }
        if (text.error_code == 0) {
            var data = text.data;
            if (data.transfer_to_kf) {
                if (!flag && typeof _mid == 'undefined') {
                    if (data.transfer_to_kf_id) {
                        $ROBOT.transferChat(parseInt(data.transfer_to_kf_id), data.transfer_to_kf_id);
                    } else {
                        $ROBOT.transferChat($config.queueId, "");
                    }
                    return html;
                } else {
                    transferFlag = true;
                }
            }
            var state = data.state;
            if (state == 1 || state == 3) {
                var answers = data.answers;
                if (answers.length > 0) {
                    robotLog("answer " + answers[0]);
                    html += answers[0];
                }
                if (data.options) {
                    var options = data.options;
                    // if (html.length > 0) html += "<br>";
                    $.each(options, function (i, option) {
                        robotLog("options[" + i + "] " + option);
                        html += addclick((i + 1), option);
                    })
                }

                if (data.related_questions && data.related_questions.length > 0) {
                    html += i18n.robot.relatedQuestions;
                    $.each(data.related_questions, function (i, relatedQuestion) {
                        robotLog("relatedQuestion[" + i + "] " + relatedQuestion);
                        html += addclick((i + 1), relatedQuestion);
                    })
                } else {
                    if (data.hot_questions && data.hot_questions.length > 0) {
                        html += i18n.robot.hotQuestions;
                        $.each(data.hot_questions, function (i, hotQuestion) {
                            robotLog("hotQuestion[" + i + "] " + hotQuestion);
                            html += addclick((i + 1), hotQuestion);
                        })
                    } else {
                        robotLog(i18n.robot.noAnswer);
                    }
                }
            } else if (state == 2) {
                var recommends = data.recommend;
                if (recommends.length > 0) {
                    html = i18n.robot.recommendsQuestions;
                    $.each(recommends, function (i, recommend) {
                        robotLog("recommend[" + i + "] " + recommend);
                        html += addclick((i + 1), recommend);
                    })
                } else {
                    robotLog(i18n.robot.noAnswer);
                }
            } else {
                robotLog(i18n.robot.noAnswer);
            }
        } else {
            robotLog(i18n.robot.error.format(text.error_code));
        }
        if (transferFlag) html = "";
        return html;
    }

    function handleXiaoIbotData(messageId, text, flag) {
        $ROBOT.robotOrderObj = {};
        var show = false;
        if (robotVersion) show = true;
        try {
            var html = '';
            var content = "";
            if (text.result)
                text = text.result;
            if ('fsg' == robotVersion) {
                if (text.code == 200) {
                    text = text.data;
                } else {
                    return;
                }
            }
            if (text && text.content) {
                content = text.content;
            }
            if ('uniqlo' == robotVersion) {
                if (text.robotName) {
                    Constants.robot.robotName = text.robotName;
                }
                if (text.robotType) {
                    Constants.robot.robotType = text.robotType;
                }
            }
            switch (text.type) {
                case 0:
                    if (!flag) {
                        if (robotVersion && typeof _mid == 'undefined') {
                            if (lastReplyIsDefault) {
                                if (roundTime >= sessionRound) {
                                    $ROBOT.transferChat($config.queueId, "");
                                }
                            } else {
                                if (roundTime > 0) roundTime = 0;
                            }
                            lastReplyIsDefault = true;
                            if (lastReplyIsDefault) roundTime++;
                        }
                    }
                    html = content;
                    break;
                case 1: //标准回复
                    lastReplyIsDefault = false;
                    var commands = text.commands;
                    $.each(commands, function (c, args) {
                        var flagForState = false;
                        if ('uniqlo' == robotVersion) {
                            flagForState = true;
                        } else {
                            if (args.state == 1) {
                                flagForState = true;
                            }
                        }
                        if (flagForState) {
                            var name = args.name;
                            if ('txtmsg' == name.toLowerCase()) {
                                html += args.args;
                            } else if ('imgmsg' == name.toLowerCase()) {
                                var arg = args.args;
                                html += getImageHtml(arg[2], arg[0]);
                            } else if ('imgtxtmsg' == name.toLowerCase()) { //图文信息
                                isNews = true;
                                if (args && args.args) {
                                    var arg = args.args[3];
                                    if (arg) {
                                        arg = arg.substring(9, arg.length - 3);
                                        var xmlDoc = $.parseXML(arg),
                                            $xml = $(xmlDoc),
                                            $item = $xml.find("item");
                                        html += domImageText.domImageTextHomeAppend();
                                        $.each($item, function (i, item) {
                                            var isFirst = false;
                                            if (i == 0) isFirst = true;
                                            html += domImageText.domImageText(wrapCDATA($(item).find('Title')[0].textContent),
                                                wrapCDATA($(item).find('Description')[0].textContent),
                                                wrapCDATA($(item).find('PicUrl')[0].textContent),
                                                wrapCDATA($(item).find('Url')[0].textContent), isFirst)
                                        })
                                        html += domImageText.domImageTextEndAppend();
                                    }
                                }
                            } else if ('P4' == name.toUpperCase()) {
                                var arg = args.args;
                                html += '<a target="_blank" href="' + arg[0] + '">' + arg[1] + '</a>';
                            }
                        }
                    });
                    if (typeof content == "string") {
                        if (!html)
                            html += content;
                    } else {
                        var contentType = content.type;
                        if ('uniqlo' == robotVersion) {
                            var size = content.size;
                            if (size > 0) {
                                var messageFormatOrder = '[MessageFormat data-type="orders" data-title="' + i18n.robot.orderTitle + '" data-key="uniqlo-' + new Date().getTime() + '" data-from="uniqlo"]';
                                var values = content.value;
                                var arrForOrder = [];
                                $.each(values, function (i, value) {
                                    var orderst = value.orderStatus;
                                    if (orderst == 'UNPAID') {
                                        orderst = '待付款';
                                    } else if (orderst == 'CANCELLED') {
                                        orderst = '交易取消';
                                    } else if (orderst == 'WAIT_SHIP') {
                                        orderst = '待发货/已付款';
                                    } else if (orderst == 'WAIT_PICK') {
                                        orderst = '待自提';
                                    } else if (orderst == 'PARTIAL_SHIP') {
                                        orderst = '部分发货';
                                    } else if (orderst == 'SHIPPED') {
                                        orderst = '已发货';
                                    } else if (orderst == 'FINISHED') {
                                        orderst = '交易成功';
                                    } else if (orderst == 'CLOSED') {
                                        orderst = '交易关闭';
                                    } else if (orderst == 'WAIT_DEPOSIT_PAY') {
                                        orderst = '定金未付尾款未付';
                                    } else if (orderst == 'WAIT_REST_PAY') {
                                        orderst = '定金已付尾款未付';
                                    } else if (orderst == 'REST_PAY_CANCELLED') {
                                        orderst = '定金已付交易取消';
                                    }
                                    arrForOrder.push({
                                        "content": value.productName,
                                        "key": i + 1,
                                        "title": value.productName,
                                        "imageUri": value.pictureUrl,
                                        "orderId": '订单' + value.orderId,
                                        "orderStatus": orderst,
                                        "size": value.size,
                                        "send": value.productName,
                                        "color": value.color,
                                        "quantity": value.quantity,
                                        "noReasonFlag": value.noReasonFlag,
                                        "price": value.actualUnitPrice || value.totalPrice
                                    })
                                })
                                messageFormatOrder += JSON.stringify(arrForOrder);
                                messageFormatOrder += '[/MessageFormat]';
                                html = $ROBOT.parseFormattedMsg(messageFormatOrder);
                            }
                        }
                    }
                    break;
                case 101: //转人工客服
                    lastReplyIsDefault = false;
                    robotLog("转人工" + content);
                    show = false;
                    if (typeof content == "string") {
                        if (content && typeof _mid == 'undefined') {
                            if (content == 'SFYZ' || content == 'SJSFYZ' || content == 'SJYZ') { //进行身份校验
                                if (!flag) {
                                    //如果是小程序中的界面的话需要向小程序发送数据给小程序作为交互, 小程序收到数据之后做页面显示用
                                    if (window.__wxjs_environment === 'miniprogram') { //判断是否是小程序
                                        var user = $config.user;
                                        if (user && user.stringfield16 == 'NO') {
                                            var urlOne = '/mainPackage/login/index?type=onlinechat&sessionid=' + $config.sessionId + '&custguid=' + $config.client.clientId;
                                            wx.miniProgram.navigateTo({
                                                url: urlOne,
                                                success: function () {
                                                    wx.miniProgram.postMessage({
                                                        data: {
                                                            code: "success",
                                                            success: 'sendMessage is success'
                                                        }
                                                    })
                                                },
                                                fail: function (e) {
                                                    wx.miniProgram.postMessage({
                                                        data: {
                                                            code: "fail",
                                                            fail: e
                                                        }
                                                    })
                                                }
                                            })
                                        } else if (user && user.stringfield16 == 'YK') {
                                            var urlTwo = '/mainPackage/register/stepTwo?type=onlinechat&userType=potentialCustomer&sessionid=' + $config.sessionId + '&custguid=' + $config.client.clientId;
                                            wx.miniProgram.navigateTo({
                                                url: urlTwo,
                                                success: function () {
                                                    wx.miniProgram.postMessage({
                                                        data: {
                                                            code: "success",
                                                            success: 'sendMessage is success'
                                                        }
                                                    })
                                                },
                                                fail: function (e) {
                                                    wx.miniProgram.postMessage({
                                                        data: {
                                                            code: "fail",
                                                            fail: e
                                                        }
                                                    })
                                                }
                                            })
                                        }
                                    } else { //非小程序的时候是直接打开配置的身份校验的地址的
                                        var url = $config.queue.sfjyUrl + '&f1=' + $config.client.clientId + '&f2=' + $config.sessionId + '&f3=' + content;
                                        if ($config.mobile)
                                            setContentIframe(url);
                                        else
                                            window.open(url);
                                    }
                                }
                            } else if (content.indexOf("ZRG") > -1) {
                                if (!flag && typeof _mid == 'undefined' && messageId - maxHisMessageId > 0) {
                                    if (!_transfering) {
                                        $ROBOT.transferChat($config.queueId, content);
                                    }
                                } else {
                                    html = ORDER_MESSAGE;
                                }
                            } else {
                                if ($config.sfyzUrl) {
                                    $.post("jsp/standard/robotZrgContentManager.jsp", {
                                        "queue": $config.queueId,
                                        "content": content,
                                        "userid": $config.client.clientId,
                                        "sessionid": $config.sessionId
                                    }, function (data) {
                                        if (typeof data == 'object') {
                                            if (data && data.message) {
                                                if ($config.mobile) {
                                                    $ROBOT_MOBILE.appendTextToDiv("clientResponseDiv", $ROBOT_MOBILE.formatNotice(data.message));
                                                } else {
                                                    $F.formatAndShowNotice(data.message);
                                                }
                                            }
                                            if (data && data.code && data.code == 'CLOSECHAT') {
                                                if (!flag) {
                                                    if (!_sessionActive) {
                                                        endSessionBtnClickHandler();
                                                    }
                                                } else {
                                                    html = ORDER_MESSAGE;
                                                }
                                            }
                                        } else {
                                            try {
                                                data = JSON.parse(data);
                                                if (data && data.message) {
                                                    if ($config.mobile) {
                                                        $ROBOT_MOBILE.appendTextToDiv("clientResponseDiv", $ROBOT_MOBILE.formatNotice(data.message));
                                                    } else {
                                                        $F.formatAndShowNotice(data.message);
                                                    }
                                                }
                                                if (data && data.code && data.code == 'CLOSECHAT') {
                                                    if (!flag) {
                                                        if (!_sessionActive) {
                                                            endSessionBtnClickHandler();
                                                        }
                                                    } else {
                                                        html = ORDER_MESSAGE;
                                                    }
                                                }
                                            } catch (e) {
                                                if (!data.startWith("<")) {
                                                    if ($config.mobile) {
                                                        $ROBOT_MOBILE.appendTextToDiv("clientResponseDiv", $ROBOT_MOBILE.formatNotice(data));
                                                    } else {
                                                        $F.formatAndShowNotice(data);
                                                    }
                                                }
                                            }
                                        }
                                    });
                                } else {
                                    html += content;
                                }
                            }
                        }
                    } else {
                        if (!flag) {
                            if (content.acs) {
                                if (messageId - maxHisMessageId > 0) {
                                    _continueChat.can = true;
                                    var url = Constants.lm.hrefClick || Constants.lm.hrefUrl;
                                    // if (url) location.href = url + '&sessionId=' + $config.sessionId + '&cmdType=' + encodeURIComponent(JSON.stringify(content));
                                    if (url) {
                                        url = url + '&sessionId=' + $config.sessionId + '&cmdType=' + encodeURIComponent(JSON.stringify(content));
                                        if ($config.mobile)
                                            setContentIframe(url);
                                        else
                                            window.open(url);
                                    }
                                }

                            }
                        }
                    }

                    // else {
                    //     $ROBOT.transferChat($config.queueId, '');
                    // }
                    break;
                default:
                    lastReplyIsDefault = false;
                    html = content;
                    break;
            }
            if (show) {
                if (slimContent) {
                    html = '<div class="slim-flag">' + html + '</div>';
                }
                var relatedQuestions = text.relatedQuestions;
                if (relatedQuestions && relatedQuestions.length > 0) {
                    html += '<div class="relate_title">' + i18n.robot.relatedQuestions + '</div>';
                    html += '<div class="relate_body"><ul>';
                    $.each(relatedQuestions, function (j, item) {
                        html += '<li><a class="relate_body_li">' + item + '</a></li>'
                        $ROBOT.robotOrderObj[j] = item;
                    })
                    html += '</ul></div>';
                }
            }

            if ('uniqlo' == robotVersion) {
                if (text.buttonList) {
                    var buttonList = text.buttonList;
                    if (buttonList.length > 0) {
                        if (text.type != 11)
                            html += '<div class="relate_title">' + i18n.robot.relatedButtonListTitle + '</div>';
                        $.each(buttonList, function (j, button) {
                            html += '<li><a class="relate_body_li"' +
                                ' data-msg="' + button.name + '"' +
                                ' data-search="' + button.question + '"' +
                                ' data-extra="' + button.type + '"' +
                                ' >' + button.name + '</a></li>'
                            $ROBOT.robotOrderObj[j] = button.question;
                        })
                    }
                }
            }
            return html;
        } catch (e) {
            robotLog(e.message, 'on handleXiaoIData')
            return '';
        }
    }

    function handleYibotData(text, flag) {
        var html = '';
        if (text.status == 0) {
            if (text.type == 200) {
                var result = text.info[0];
                if (result.answer == 'zrg') { //转人工
                    if (!$config.hasCreateChat) {
                        if (!flag && typeof _mid == 'undefined') {
                            robotLog("转人工操作");
                            if ($config.mobile) {
                                $ROBOT.transferChat($config.queueId);
                            } else {
                                $F.showConfirm(tip, function () {
                                    // TODO 弹框提示是否需要转接到人工坐席
                                    $ROBOT.transferChat($config.queueId);
                                });
                            }
                        } else {
                            html = ORDER_MESSAGE;
                        }
                        $config.hasCreateChat = true;
                    } else {
                        domImageText.setNotices(i18n.robot.hasTransferAgent);
                        delayNotice();
                    }
                    return;
                }
                if ('image-text' == result.answerType) {
                    var answerjson = result.answerjson;
                    if (answerjson.length > 0) {
                        isNews = true;
                        html += domImageText.domImageTextHomeAppend();
                        $.each(answerjson, function (i, item) {
                            var isFirst = false;
                            if (i == 0) isFirst = true;
                            html += domImageText.domImageText(item.title, item.desc, item.pic_url, item.url, isFirst)
                        })
                        html += domImageText.domImageTextEndAppend();
                    }
                } else if ("single-image" == result.answerType) {
                    var imageUrl = result.pic_url;
                    html = getImageHtml(imageUrl, "");
                } else {
                    html = result.answer;
                }

                var relate = result.relate;
                if (relate && relate.length > 0) {
                    html += '<div class="relate_title">' + i18n.robot.relatedQuestions + '</div>';
                    html += '<div class="relate_body"><ul>';
                    $ROBOT.robotOrderObj = {};
                    $.each(relate, function (j, item) {
                        html += '<li><a  class="relate_body_li">' + item.qt + '</a></li>'
                    })
                    html += '</ul></div>';
                }
            } else if (text.type == 300) {
                var resultArr = text.info;
                if (resultArr) {
                    html += '<div class="relate_title">' + i18n.robot.relatedQuestions + '</div>';
                    $.each(resultArr, function (i, result) {
                        html += domAnswerTitleAppend(result.question, result.question, result.answer, "", i);
                    })
                }
            } else if (text.type == 400) { //机器人调用接口返回的结果
                var resultArr = text.info;
                $.each(resultArr, function (i, info) {
                    if (info && info.answer) {
                        var answers = info.answer;
                        if ($.isArray(answers)) {
                            $.each(answers, function (i, answer) {
                                if (answer) {
                                    html += numberConvertToUppercase(i + 1) + ':';
                                    var policeRs = i18n.common.robotTemplateForPolicy;
                                    $.each(answer, function (key, value) {
                                        policeRs = policeRs.replaceAll("{" + key + "}", value)
                                    })
                                    html += policeRs;
                                }
                            })
                        }
                    }
                })
            } else {
                robotLog('YiBot 接口异常，请联系开发人员。');
                domImageText.setNotices(i18n.robot.error);
                delayNotice();
            }
            var relate = text.relate;
            if (relate && relate.length > 0) {
                html += '<div class="relate_title">' + i18n.robot.relatedQuestions + '</div>';
                html += '<div class="relate_body"><ul>';
                $ROBOT.robotOrderObj = {};
                $.each(relate, function (j, item) {
                    html += '<li><a href="javascript:void(0);" class="relate_body_li">' + item.qt + '</a></li>'
                });
                html += '</ul></div>';
            }
            if (!flag) {
                var showNoticeForTransferMessage = false;
                var showNoticeForTransferMessageWhenRejectRecog = false;

                if (text.session_round) {
                    var selfSessionRound = text.session_round
                    if (selfSessionRound == sessionRound) {
                        showNoticeForTransferMessage = true;
                    }
                }
                if (!showNoticeForTransferMessage && text.reject_recog) {
                    var rejectRecog = text.reject_recog
                    if (rejectRecog == 1) {
                        showNoticeForTransferMessage = true;
                        showNoticeForTransferMessageWhenRejectRecog = true;
                    }
                }
                if (showNoticeForTransferMessage) {
                    if (showNoticeForTransferMessageWhenRejectRecog) {
                        html = html + getNoticeForTransferMessage();
                    } else {
                        html = html + getNoticeForTransferMessageWhenRejectRecog();
                    }
                }
            }
        }

        return html;
    }

    function handleSobotData(text, flag) {
        var html = "";
        if (text && text.code == "1000") {
            if (!flag && text.data.transfer_type == 1 || text.data.transfer_type == 2 || text.data.transfer_type == 3) {
                html += text.data.answer;
            } else if (!flag && text.data.transfer_type == 99) {
                var tQueue_ID = "";
                if (text.data.queue_id) {

                    html = isEmpty(text.data.answer) ? i18n.robot.hasTransferAgent : text.data.answer;
                    tQueue_ID = text.data.queue_id;
                } else {
                    for (var i = 0; i < $config.queue.robotEngineConfig.queues.length; i++) {
                        if (text.data.queue_name == $config.queue.robotEngineConfig.queues[i].queue_name) {

                            html = text.data.answer;
                            tQueue_ID = $config.queue.robotEngineConfig.queues[i].queue_id;
                            break;
                        }
                    }

                    html = isEmpty(text.data.answer) ? i18n.robot.hasTransferAgent : text.data.answer;
                    tQueue_ID = isEmpty(tQueue_ID) ? isEmpty(text.data.transfer_queue) ? $config.queueId : text.data.transfer_queue : tQueue_ID;
                }
                console.log('机器人转人工队列:' + tQueue_ID);
                $ROBOT.transferChat(tQueue_ID, tQueue_ID);
            } else {
                var data = text.data;
                if (data && data.answer)
                    html = data.answer;
                var suggestions = data.suggestions;
                if (suggestions && suggestions.length > 0) {
                    if (data.stripe)
                        html += '<div class="relate_title">' + data.stripe + "</div>";
                    else
                        html += '<div class="relate_title">' + i18n.robot.relatedQuestions + "</div>";
                    $.each(data.suggestions, function (i, suggestion) {
                        var answer = suggestion.answer;
                        answer += getTranseferButtonHtml(flag);
                        html += addclick(i + 1, suggestion.question)
                    })
                }
                if (!flag) {
                    html += getTranseferButtonHtml(flag);
                    var htmlData = " ";
                    if (data.docId)
                        htmlData += 'data-docid="' + data.docId + '" ';
                    if (data.msgId)
                        htmlData += 'data-msgid="' + data.msgId + '" ';
                    if (data.cid)
                        htmlData += 'data-cid="' + data.cid + '" ';
                    if (data.uid)
                        htmlData += 'data-uid="' + data.uid + '" ';
                    if (data.question)
                        htmlData += 'data-docname="' + data.question + '" ';
                    html += getLikeAndStepButtonHtml("", ROBOT_ID.SOBOT, htmlData)
                }
            }
        } else {
            // 当机器人异常是自动转人工
            html += "<p><strong>已为您转入人工客服队列，请您选择需要咨询的问题类型：</strong></p>"
            for (var i = 0; i < $config.queue.robotEngineConfig.queues.length; i++) {
                html += '<p><a class="transfer-message" data-message="' + $config.queue.robotEngineConfig.queues[i].queue_name + '" data-extra="' + $config.queue.robotEngineConfig.queues[i].queue_id + '"' + '" style="margin-top: 0px;">' + $config.queue.robotEngineConfig.queues[i].queue_name + '</a></p>';
            }
        }
        return html
    }

    function isEmpty(e) {
        return (e == undefined || e == null || (typeof (e) == "string" && $.trim(e) == ""));
    }

    function handleElitebotData(text, flag) {
        var html = "";
        if (text && text.code == 1) {
            var value = text.value;
            if (value.msgtype == "text") {
                var text = value.text;
                if (text) {
                    html = wrapURL(text.content);
                } else {
                    html = i18n.robot.noAnswer;
                    html += getTranseferButtonHtml(flag);
                }
            } else if (value.msgtype == "image") {
                var image = value.image;
                if (image) {
                    var src = robotEngineConfig.serverUrl + "/image?file=" + image.media_id;
                    html = getImageHtml(src, '');
                } else {
                    html = i18n.robot.noImage;
                    if (!flag) {

                    }
                }
            } else if (value.msgtype == 'news') {
                var news = value.news;
                if (news) {
                    var articales = news.articles;
                    if (articales.length > 0) {
                        var property = robotEngineConfig.property;
                        var baseUrl = "";
                        if (property) {
                            baseUrl = property.baseUrl;
                        }
                        html += domImageText.domImageTextHomeAppend();
                        $.each(articales, function (i, article) {
                            var picurl = article.picurl;
                            if (!picurl.startWith('http')) {
                                picurl = baseUrl + picurl;
                            }
                            var description = article.description;
                            var title = article.title;
                            var url = article.url;
                            var isFirst = false;
                            if (i == 0) {
                                isFirst = true;
                            }
                            html += domImageText.domImageText(title, description, picurl, url, isFirst)
                        })
                        html += domImageText.domImageTextEndAppend();
                    }

                }
            } else if ('music' == value.msgtype) {

            } else if ('video' == value.msgtype) {
                var video = value.video;
                var src = robotEngineConfig.serverUrl + "/video?file=" + video.media_id;
                html += "<video src='" + src + "'>"
            } else {
                html = value;
            }
        } else {
            html = text.message || i18n.robot.error;
        }
        return html;
    }

    function handleEbossKMbotData(text, flag) {
        var feedback = {
            topNum: 1,
        };
        var html = "";
        if (text && text.success) {
            var data = text.data;
            if (data) {
                if (data.question) {
                    feedback.question = data.question;
                }
                html = data.answer;
                if (data.label) {
                    feedback.chooseLabel = data.label;
                    feedback.topLabel = data.label;
                }
                var turnToSomeb = data.turnToSomeb;
                if (turnToSomeb && typeof _mid == 'undefined') {
                    $ROBOT.transferChat($config.queueId, "");
                }
            } else {
                html = text.alertMsg || i18n.robot.noAnswer;
            }
        } else {
            html = text.alertMsg || i18n.robot.error;
        }
        if (!flag) {
            html += getLikeAndStepButtonHtml("", ROBOT_ID.KMBOT);
        }
        sendFeedback(JSON.stringify(feedback));
        return html;
    }

    function handleEliteAIbotData(texts, flag) {
        var htmlArr = [];
        if (texts) {
            if (texts.code == 0)
                texts = texts.value;
            $.each(texts, function (i, text) {
                if (text.hasAnswer) {
                    var html = '';
                    if (text) {
                        var type = text.type;
                        switch (type) {
                            case 'text':
                                html = text.text;
                                html = html.replace(/&lt;/g, "<").replace(/&gt;/g, ">");
                                html = wrapATagAddTarget(html);
                                html = '<div class="msg-text">' + html + '</div>';
                                break;
                            case 'choice':
                                var buttonType = text.buttonType;
                                html = '<div class="msg-text">' + text.text + '</div>';
                                if (text.choices) {
                                    // html += "<br>";
                                    $.each(text.choices, function (i, button) {
                                        if (buttonType == 1) {
                                            html += addclick((i + 1), button.title);
                                        } else {
                                            html += addclick(0, button.title);
                                        }

                                    })
                                }
                                break;
                            case 'textImg':
                                html += domImageText.domImageTextHomeAppend();
                                $.each(text.textImg, function (i, item) {
                                    var isFirst = false;
                                    if (i == 0) isFirst = true;
                                    html += domImageText.domImageText(item.menuTitleContent, item.menuHintContent, item.menuImgURL, item.menuContentURL, isFirst)
                                })
                                html += domImageText.domImageTextEndAppend();
                                break
                            case 'cmd':
                                if (!flag && typeof _mid == 'undefined') {
                                    var robotText = text.text;
                                    if (robotText.indexOf("zrg") > -1) {
                                        if ($ROBOT.isPocVersion()) {
                                            $("#popDiv").show();
                                        } else {
                                            $ROBOT.transferChat($config.queueId, robotText);
                                        }
                                    } else if (robotText == 'hangup') { //显示满意度
                                        if (_sessionActive) {
                                            judgeShowRate(Constants.rate.rateType.CLIENT_SEND);
                                            endSessionBtnClickHandler();
                                        }
                                    }
                                } else {
                                    html = ORDER_MESSAGE;
                                }
                                break;
                            default:
                                html = text;
                                break;
                        }
                    } else {
                        html = i18n.robot.error;
                    }
                    if (!flag && html) {
                        html += getLikeAndStepButtonHtml("", ROBOT_ID.ELIEAI);
                    }
                    // sendFeedback(JSON.stringify(feedback));
                    htmlArr.push(html);
                }
            })
        } else {
            htmlArr.push(i18n.robot.error);
        }

        return htmlArr;
    }

    function handleZTEROBOTData(text, flag) {

        var account = UCSSSOAccount || ZTEDPGSSOUser;
        if (account == "") {
            var cookies = document.cookie;
            if (cookies.length > 0) {
                var cookieArr = cookies.split(";");
                $.each(cookieArr, function (i, cookie) {
                    var param = cookie.trim().split('=');
                    if (param[0] == 'UCSSSOAccount') {
                        UCSSSOAccount = param[1];
                    } else if (param[0] == 'ZTEDPGSSOUser') {
                        ZTEDPGSSOUser = param[1];
                    }
                });
            }
            account = UCSSSOAccount || ZTEDPGSSOUser;
        }

        var html = "";
        var htmlData = ' data-reason="" data-advice="" ';
        if (!text) {
            html = i18n.robot.error;
        }
        text = text.result;
        if (text.reply) {
            htmlData += ' data-answer="' + encodeURIComponent(text.reply) + '" ';
            html = text.reply;
        }
        if (text.rawQuery) {
            htmlData += ' data-query="' + encodeURIComponent(text.rawQuery) + '" ';
        }
        html = html.replaceAll("\\t", "").replaceAll("\n", "");
        if (html == '') {
            if (text.recommends) {
                var recommendResult = text.recommends;
                if (recommendResult.length > 0) {
                    html += i18n.robot.relatedQuestions;
                    $.each(recommendResult, function (i, recommend) {
                        html += addclick(i + 1, recommend.question);
                    })
                }
            }
        }
        if (html == '') {
            if (robotEngineConfig.noAnswerMessage)
                html = robotEngineConfig.noAnswerMessage;
        }
        if (account) {
            htmlData += ' data-account="' + account + '" ';
            html += getLikeAndStepButtonHtml("", ROBOT_ID.ZTEROBOT, htmlData);
        }
        // sendFeedback(JSON.stringify(feedback));
        return html;
    }

    function handleSinoROBOTData(text, flag) {
        var html = "";
        if (!text) {
            html = i18n.robot.error;
        }
        if (text) {
            var result = text.result;
            if (result == 0) {
                var answerTypeId = text.answerTypeId;
                if (answerTypeId == 6) { //直接回答
                    if (text.singleNode) {
                        var singleNode = text.singleNode;
                        var answerMsg = singleNode.answerMsg;
                        var isRichText = singleNode.isRichText;
                        if (isRichText == 1) {
                            var xmlDoc = $.parseXML(answerMsg),
                                $xml = $(xmlDoc),
                                $item = $xml.find("root");
                            html += domImageText.domImageTextHomeAppend();
                            $.each($item, function (i, item) {
                                var isFirst = false;
                                if (i == 0) isFirst = true;
                                html += domImageText.domImageText(wrapCDATA($(item).find('Title')[0].textContent),
                                    wrapCDATA($(item).find('Description')[0].textContent),
                                    wrapCDATA($(item).find('PicUrl')[0].textContent),
                                    wrapCDATA($(item).find('Url')[0].textContent), isFirst)
                            })
                            html += domImageText.domImageTextEndAppend();
                        } else {
                            html = answerMsg;
                        }
                        if (singleNode.cmd) {
                            if (!flag) {
                                var cmd = singleNode.cmd;
                                if (cmd.toUpperCase().indexOf("ZRG") > -1) {
                                    $ROBOT.transferChat($config.queueId, cmd);
                                }
                                if (cmd.toUpperCase().indexOf("IVR") > -1) {
                                    $ROBOT.transferChat($config.queueId, cmd);
                                }
                            }
                        }
                    }
                    if (text.vagueNode) {
                        var vagueNode = text.vagueNode;
                        var listItems = vagueNode.itemList;
                        if (listItems.length > 0) {
                            html += vagueNode.promptVagueMsg + "<br>";
                            $.each(listItems, function (i, listItem) {
                                html += addclick(i + 1, listItem.question);
                            })
                            html += vagueNode.endVagueMsg;
                        }

                    }
                } else { //1  系统错误 2  答案缺失 3  无法回答 4  有敏感词 5 推荐回答  7  模式匹配  8命中图谱 9  命中场景 10 聊天过频
                    if (text.singleNode) {
                        var singleNode = text.singleNode;
                        html = singleNode.answerMsg;
                        if (singleNode.cmd) {
                            var cmd = singleNode.cmd;
                            if (cmd.toUpperCase().indexOf("ZRG") > -1) {
                                html = html + getNoticeForTransferMessageWhenRejectRecog();
                            }
                            if (cmd.toUpperCase().indexOf("IVR") > -1) {
                                html = html + getNoticeForTransferMessageWhenRejectRecog();
                            }
                        }
                    }
                    if (text.vagueNode) {
                        var vagueNode = text.vagueNode;
                        html += vagueNode.promptVagueMsg;
                        var listItems = vagueNode.itemList;
                        $.each(listItems, function (i, listItem) {
                            html += addclick(i + 1, listItem.question);
                        })
                        html += vagueNode.endVagueMsg;
                    }
                }
                var serviceLogId = text.serviceLogId;
                if (serviceLogId) {
                    htmlData = ' data-serviceLogId="' + serviceLogId + '" ';
                    html += getLikeAndStepButtonHtml("", ROBOT_ID.SINOROBOT, htmlData);
                }

            } else {
                html = i18n.robot.error;
            }
        }
        if (html == '') {
            if (robotEngineConfig.noAnswerMessage)
                html = robotEngineConfig.noAnswerMessage;
        }

        // sendFeedback(JSON.stringify(feedback));
        return html;
    }

    function handleEemotiBOTData(text, flag) {
        var feedback = false;
        var html = "";
        if (!text) {
            html = i18n.robot.error;
        }
        if (text) {
            var status = text.status;
            if (status == 200) {
                var datas = text.data;
                $.each(datas, function (i, data) {
                    var type = data.type;
                    var subType = data.subType;
                    if (type == 'text') { //直接回答
                        if ('text' == subType) {
                            html += wrapClickMessage(data.value);
                        } else if ('recommend' == subType) {
                            var dataRecommends = data.data;
                            $.each(dataRecommends, function (j, remmend) {
                                html += remmend.replyText;
                            })
                        } else if ('relatelist' == subType) {
                            var dataAbout = data.data;
                            html += data.value;
                            $.each(dataAbout, function (l, about) {
                                html += '<div class="send-message" data-message="' + about + '">' + about + '</div>';
                            })
                        }
                    } else if (type == 'cmd') { //命令
                        if (subType == 'human') {
                            if (data.value) {
                                html = data.value;
                                if (!flag && typeof _mid == 'undefined') {
                                    if (data.answerType) {
                                        $ROBOT.transferChat($config.queueId, data.answerType);
                                        feedback = false;
                                    }
                                }
                            } else {
                                if (!flag && typeof _mid == 'undefined') {
                                    $ROBOT.transferChat($config.queueId, data.answerType);
                                    feedback = false;
                                }
                            }
                        }
                    }
                    // else if(type == 'relatelist'){
                    //     if (data.value) {
                    //         html = data.value;
                    //
                    //     }
                    // }
                })
            } else {
                html = i18n.robot.error;
            }
            var info = text.info;
            if (text.info && text.info.module && 'faq' == text.info.module)
                feedback = true;
        }
        if (html == '') {
            if (robotEngineConfig.noAnswerMessage)
                html = robotEngineConfig.noAnswerMessage;
        }
        if (!flag && feedback) {
            if (text.customInfo) {
                var customInfo = text.customInfo;
                var dom = 'data-uuid= "' + (customInfo.uuid || '') + '"';
                html += getLikeAndStepButtonHtml("", ROBOT_ID.EMOTIBOT, dom);
            }
        }
        // sendFeedback(JSON.stringify(feedback));
        return html;
    }

    function handleYunwBOTData(text, flag) {
        var property = robotEngineConfig.property;
        var original = false;
        if (property.original) {
            original = property.original;
        }
        var html = "";
        if (text.status == 0) {
            var data = text.data;
            var serviceType = data.serviceType;
            var robotReply = data.robotReply;
            robotReply = robotReply[0];
            var msgType = robotReply.msgtype;
            switch (msgType) {
                case 'text':
                    var content = robotReply.text;
                    html = content.content;
                    break;
                case 'image':
                    var image = robotReply.image;
                    html = getImageHtml(image.url, image.name);
                    html += image.content;
                    break;
                case 'voice':
                    var voice = robotReply.voice;
                    html = '<div class="message-voice" data-url="' + voice.url + '" ></div>';
                    html += voice.content;
                    break;
                case 'video':
                    var video = robotReply.video;
                    html = '<div class="mobileVideo" data-url="' + video.url + '">' +
                        '<span>video.name</span>' +
                        '<i class="play far fa-play-circle"></i>' +
                        '</div>';
                    html += video.content;
                    break;
                case 'news':
                    var news = robotReply.news;
                    html += domImageText.domImageTextHomeAppend();
                    $.each(news.articles, function (i, article) {
                        var isFirst = false;
                        if (i == 0) isFirst = true;
                        html += domImageText.domImageText(article.title, article.description, article.picurl, article.url, isFirst);
                    })
                    html += domImageText.domImageTextEndAppend();
                    break;
                case 'guide':
                    var guide = robotReply.guide;
                    if (original) {
                        if (guide.beforeWord)
                            html += guide.beforeWord;
                        $.each(guide.list, function (i, listItem) {
                            html += addclick(listItem.seq, listItem.question);
                        })
                        if (guide.afterWord)
                            html += guide.afterWord;
                    } else {
                        if (guide.content)
                            html += guide.content;
                    }

                    break;
                case 'richText':
                    var richText = robotReply.richText;
                    if (original) {
                        html += richText.original
                    } else {
                        html += domImageText.domImageTextHomeAppend();
                        html += domImageText.domImageText(richText.title, richText.description, richText.picurl, richText.url, true);
                        html += domImageText.domImageTextEndAppend();
                    }
                    break;
                default:
                    html = JSON.parse(robotReply);
                    break;
            }
            if (robotReply.recommendQuestion) {
                var recommendQuestion = robotReply.recommendQuestion;
                if (recommendQuestion.beforeWord)
                    html += recommendQuestion.beforeWord;
                $.each(recommendQuestion.list, function (i, listItem) {
                    html += addclick(listItem.seq, listItem.question);
                })
                if (recommendQuestion.afterWord)
                    html += recommendQuestion.afterWord;
            }
            if (robotReply.satisfaction) {
                html += robotReply.satisfaction;
            }
            if ('seat' == serviceType && !flag) {
                $ROBOT.transferChat($config.queueId, "");
            }
        } else {
            html = text.message
        }
        html = $EMOTION.parseToUnicode(html);
        return html;
    }

    function handleECHATBOTData(text, flag) {
        var html = JSON.stringify(text);
        if (text) {
            if (typeof text == "string") {
                text = JSON.parse(text);
            }
            if (text.plainContent)
                text = text.plainContent;
            var msgType = text.msgType;
            if (msgType) {
                switch (msgType) {
                    case 'text':
                        var content = text.text;
                        html = content.content;
                        break;
                    case 'image':
                        var image = text.image;
                        html = getImageHtml(image.picUrl, '');
                        break;
                    case 'voice':
                        var voice = text.voice;
                        html = '<div class="message-voice" data-url="' + voice.fileUrl + '" data-length="' + voice.duration + '" ></div>';
                        break;
                    case 'video':
                        var video = text.video;
                        html = '<div class="mobileVideo" data-url="' + video.fileUrl + '">' +
                            '<span>video.name</span>' +
                            '<i class="play far fa-play-circle"></i>' +
                            '</div>';
                        break;
                    case 'file':
                        var file = text.file;
                        html = '<a href = "' + file.fileUrl + '" target = "_blank" class="attachment">' + file.fileName + '</a>';
                        break;
                    case 'news':
                        var news = text.news;
                        html = domImageText.domImageTextHomeAppend();
                        html += domImageText.domImageText(news.title, news.content, news.imageUrl, news.url, true);
                        html += domImageText.domImageTextEndAppend();
                        break;
                    case 'location':
                        var location = text.location;
                        html = '<div class="message-location" data-latitude="' + location.locationX + ' data-longitude="' + location.locationY + ' data-address="' + location.label + '"></div>';
                        break;
                    case 'robotSimilarMatch':
                        if (text.hint)
                            html = text.hint;
                        if (text.suggestions) {
                            var suggestions = text.suggestions;
                            $.each(suggestions, function (i, suggestion) {
                                html += addclick(i + 1, suggestion.question);
                            })
                        }
                        break;
                    case 'regChat':
                        html = '';
                        break;
                    case 'endChat':
                        html = '';
                        break;
                    case 'chatStarted':
                        html = '';
                        break;
                    case 'chatEnded':
                        html = '';
                        break;
                    case 'commitEvaluate':
                        html = '';
                        break;
                    case 'transferCmd':
                        if (!flag && typeof _mid == 'undefined') {
                            var content = text.content;
                            $ROBOT.transferChat($config.queueId, content);
                            html = "";
                        } else {
                            html = text.content;
                        }
                        break;
                    default:
                        var content = text.content;
                        if (content) {
                            html = content;
                        }
                        break;
                }
            }
        }
        return html;
    }

    function handleDKNTBOTData(text, flag) {
        var html = JSON.stringify(text);
        if (text) {
            if (typeof text == "string") {
                text = JSON.parse(text);
            }
            var msgType = text.msgType;
            if (msgType) {
                switch (msgType) {
                    case 'text':
                        html = text.content;
                        break;
                    case 'image':
                        var image = text.image;
                        html = getImageHtml(image.picUrl, '');
                        break;
                    case 'voice':
                        var voice = text.voice;
                        html = '<div class="message-voice" data-url="' + voice.fileUrl + '" data-length="' + voice.duration + '" ></div>';
                        break;
                    case 'video':
                        var video = text.video;
                        html = '<div class="mobileVideo" data-url="' + video.fileUrl + '">' +
                            '<span>video.name</span>' +
                            '<i class="play far fa-play-circle"></i>' +
                            '</div>';
                        break;
                    case 'file':
                        var file = text.file;
                        html = '<a href = "' + file.fileUrl + '" target = "_blank" class="attachment">' + file.fileName + '</a>';
                        break;
                    case 'news':
                        var news = text.news;
                        html = domImageText.domImageTextHomeAppend();
                        html += domImageText.domImageText(news.title, news.content, news.imageUrl, news.url, true);
                        html += domImageText.domImageTextEndAppend();
                        break;
                    case 'location':
                        var location = text.location;
                        html = '<div class="message-location" data-latitude="' + location.locationX + ' data-longitude="' + location.locationY + ' data-address="' + location.label + '"></div>';
                        break;
                    case 'cmd':
                        console.log("指令消息");
                        break;
                    default:
                        var content = text.content;
                        if (content) {
                            html = content;
                        }
                        break;
                }
            }
        }
        return html;
    }

    function getSearchKey(actionCode, key) {
        var obj = {};
        if (actionCode) {
            obj["actionCode"] = actionCode;
        }
        obj["key"] = typeof key == "object" ? JSON.parse(JSON.stringify(key).replaceAll('\n', '<br>')) : key;
        var keyStr = JSON.stringify({
            key: JSON.stringify(obj)
        });
        return keyStr.substring(8, keyStr.length - 2);
    }

    /**
     * 1、富文本模版（TEXT：10000）
     2、折叠模版（FOLD：10001）
     3、图文模版（LINK: 10010）
     4、选择模版（SELECT：10018）
     5、流程表单模版（FLOWFORM：10019）
     6、快捷卡片（QUICKCARD：10016）
     7、猜你想问（GUESSCARD：10017）
     8、天气模版（sysWeather ：10005）
     * @param text
     * @param flag
     * @returns {string}
     */
    function handleYANXIBOTData(text, flag) {
        var html = '',
            answerMessageId = '';
        var text = JSON.stringify(text);
        if (text) {
            if (typeof text == "string") {
                text = JSON.parse(text);
            }
            if (text.hasOwnProperty("robotAnswerLikeSwitch")) {
                likeButton = stepButton = text.robotAnswerLikeSwitch;
                return "";
            }
            var type = text.type;
            if ('chat_message' === type) {
                if (text.messageId)
                    answerMessageId = text.messageId;
                var body = text;
                if (text.body) body = text.body;
                if (body && body.data) {
                    if (Object.keys(body.data).length != 0) {
                        var showLikeAndSteps = false;
                        var tplData = body.data.tplData;
                        if (tplData.tags && tplData.tags.sys_tag_should_evaluate) {
                            showLikeAndSteps = tplData.tags.sys_tag_should_evaluate.value.shouldEvaluate;
                            console.log("是否需要显示点赞点踩的按钮：" + showLikeAndSteps);
                        }
                        var nativeId = body.template.nativeId;
                        switch (nativeId) {
                            case '10000': //富文本模版
                                var richText = tplData.html || tplData.ops[0].insert || '';
                                html += richText;
                                break;
                            case '10001': //折叠模版
                                var options = tplData.options;
                                var classOrientation = tplData.orientation ? 'orientation' : '';
                                var clickOnce = tplData.clickOnce ? ' data-once="1" ' : '';
                                html = '<div class="relate_title ' + classOrientation + '">' + tplData.message + '</div>';
                                if (options && options.length > 0) {
                                    html += '<div class="btn-group ' + classOrientation + '">';
                                    $.each(options, function (i, option) {
                                        var answerType = option.answerType;
                                        var optionValue = option.optionValue;
                                        var optionName = option.optionName;
                                        if (answerType == 1) {
                                            html += '<div class="robot-btn show-iframeUrl" ' + clickOnce + ' data-url="' + optionValue + '">' + optionName + '</div>';
                                        } else {
                                            var $type3Dom = $("<div>").addClass("robot-btn key-text")
                                                .attr('data-key', getSearchKey("ans.questionCard", option))
                                                .attr("data-value", optionName)
                                                .attr("data-type", "message")
                                                .text(optionName);
                                            if (tplData.clickOnce) $type3Dom.attr("data-once", 1);
                                            html += $("<div>").append($type3Dom).html();
                                        }
                                    })
                                    html += '</div>';
                                }

                                break;
                            case '10010': //图文模版
                                html += '<div class="message-card" data-url="' + tplData.link + '">' +
                                    '<div class="card-title">' + tplData.title + '</div>' +
                                    '<div class="card-body">' +
                                    '<div class="card-image">' +
                                    '<img class="thumb" src="' + fileUrl + tplData.icon + '">' +
                                    '</div>' +
                                    '<div class="card-content">' +
                                    '<p class="card-price">' + tplData.description + '</p>' +
                                    '<p class="card-from">' + tplData.content + '</p>' +
                                    '</div>' +
                                    '</div>' +
                                    '</div>';
                                break;
                            case '10018': //选择模版
                                var multiSelect = tplData.multiSelect;
                                if (multiSelect) {
                                    html = '<div class="robot-card">';
                                    html += '<div class="card-title">' +
                                        '<span>' + tplData.message.html + '</span>' +
                                        '</div>';
                                    html += '<div class="card-content">';
                                    $.each(tplData.items, function (i, item) {
                                        html += '<div class="card-buttonItem" data-title="' + item.value + '">' +
                                            '<span>' + item.text + '</span>' +
                                            '</div>';
                                    })
                                    html += '</div>';
                                    html += '<div class="card-button">' +
                                        '<div class="card-flex1">' +
                                        '<div class="card-btnSure card-sure" data-active="sure">确定</div>' +
                                        '</div>' +
                                        '<div class="card-flex1">' +
                                        '<div class="card-btnSure card-unsure" data-active="no">不清楚</div>' +
                                        '</div>' +
                                        '</div>';
                                    html += '</div>';

                                } else {
                                    html = tplData.message.html;
                                    $.each(tplData.items, function (i, item) {
                                        html += '<div class="send-message" data-message="' + item.value + '">' + item.text + '</div>';
                                    })
                                }
                                break;
                            case '10019': //流程表单模版
                                html = '<div class="moban-message">' + tplData.message + '</div>';
                                var form = tplData.form;
                                html += '<div class="moban-title">' + form.title + '</div>';
                                $.each(form.items, function (i, item) {
                                    html += '<div class="moban-item-name">' + item.itemName + '</div>';
                                    html += '<div class="moban-item-body">' + item.itemValue.html + '</div>';
                                })
                                var btns = tplData.btns;
                                if (btns && btns.length > 0) {
                                    var $btn = $("<div>").addClass("btn-group");
                                    $.each(btns, function (i, btn) {
                                        var $li = $("<div>").addClass("robot-btn").text(btn.text);
                                        if ('link' == btn.type) {
                                            $li.addClass('show-iframeUrl')
                                                .attr("data-url", btn.value);
                                        } else if ('message' == btn.type) {
                                            $li.addClass('send-message')
                                                .attr("data-message", btn.value);
                                        } else if ('action' == btn.type) {
                                            $li.addClass('key-text')
                                                .attr({
                                                    "data-text": btn.text,
                                                    "data-value": btn.value || btn.text,
                                                    "data-type": btn.type
                                                });
                                            if (btn.actionType == 'text') {
                                                $li.attr('data-key', getSearchKey(btn.actionCode, typeof btn.cbData.default));
                                            } else {
                                                $li.attr('data-key', getSearchKey("", btn.cbData.default));
                                            }
                                        }
                                        $btn.append($li);
                                    })
                                    html += $("<div>").append($btn).html();
                                }
                                break;
                            case '10016': //快捷卡片
                                html = tplData.html;
                                break;
                            case '10017': //猜你想问
                                $.each(tplData.items, function (i, item) {
                                    html += '<div class="send-message" data-message="' + item.value + '">' + item.text + '</div>';
                                });
                                break;
                            case '10005': //天气模版
                                html = tplData.message;
                                break;
                        }
                        if (body.transferIM && !flag) { //需要转人工
                            var transferIMType = body.transferIMType;
                            var transferInfo = {
                                "transferIMType": transferIMType,
                                "messageId": answerMessageId,
                                "dialogId": text.dialogId || '',
                            };
                            var keyStr = JSON.stringify({
                                key: JSON.stringify(transferInfo)
                            });
                            transferInfo = keyStr.substring(8, keyStr.length - 2);
                            if ('MANUAL' == transferIMType) {
                                html = html + getNoticeForTransferMessage(transferInfo);
                            } else if ('AUTO' == transferIMType) {
                                if (!flag && typeof _mid == 'undefined') {
                                    $ROBOT.transferChat($config.queueId, transferInfo);
                                }
                            }
                        } else {
                            if (!flag && html && showLikeAndSteps) {
                                var dom = 'data-evaluateType= "5" data-answerMessageId="' + answerMessageId + '"';
                                html += getLikeAndStepButtonHtml("", ROBOT_ID.YANXIBOT, dom);
                            }
                        }
                    } else {
                        html = body.content;
                        if (typeof html === "object" && html.hasOwnProperty("html")) {
                            html = html.html;
                        }
                    }
                }

            } else if ('event_message' == type) {
                if (!hasRobot) return;
                var body = text;
                if (text.body) body = text.body;
                if (body.data) {
                    var data = body.data;
                    if (body.template) {
                        var nativeId = body.template.nativeId;
                        switch (nativeId) {
                            case '10016':
                                if (!showTimeObj.quickCard) {
                                    showTimeObj.quickCard = true;
                                    if (data.tplData) {
                                        var items = data.tplData.items;
                                        if (items.length > 0) {
                                            var $quickcardHtml = $("<div>").addClass("quickcard"),
                                                $content = $("<div>").addClass("content"),
                                                $ul = $("<div>").addClass("ul");
                                            $.each(items, function (i, item) {
                                                var $li = $("<div>").addClass("li").addClass('key-text')
                                                    .data("text", item.text)
                                                    .data("value", item.value || item.text);
                                                $li.data('type', item.type);
                                                if ('action' == item.type) {
                                                    if (item.actionType == 'text') {
                                                        $li.data('key', getSearchKey(item.actionCode, item.cbData.default));
                                                    } else {
                                                        $li.data('key', getSearchKey("", item.cbData.default));
                                                    }
                                                }
                                                var $item = $("<div>").addClass("item"),
                                                    $topImg = $("<div>").addClass("topImg").append($("<img>").addClass('avatar').attr('src', fileUrl + item.params.icon)),
                                                    $font = $("<div>").addClass("font").text(item.text);
                                                $item.append($topImg).append($font);
                                                $li.append($item);
                                                $ul.append($li);
                                            })
                                            $quickcardHtml.html($content.html($ul));
                                            domImageText.appendDom($quickcardHtml);
                                        }
                                    }
                                }
                                break;
                            case '10017':
                                if (!showTimeObj.guessCard) {
                                    showTimeObj.guessCard = true;
                                    if (data.tplData) {
                                        if (data.tplData) {
                                            var items = data.tplData.items;
                                            if (items.length > 0) {
                                                guessYouWantAskArr = items;
                                                guessYouWantAskPageMax = items.length;
                                                html = getGuessYouAsk();
                                            }
                                        }
                                    }
                                }
                                break;
                        }
                    } else {
                        var content = text.content;
                        var code = body.action.code;
                        if ("cfg.quickEntry" == code) { //快捷入口
                            if (!showTimeObj.quickEntry) {
                                showTimeObj.quickEntry = true;
                                if (data.tplData) {
                                    var items = data.tplData.items;
                                    if (items.length > 0) {
                                        var $keysHtml = $('<ul>');
                                        $.each(items, function (i, item) {
                                            var $li = $("<li>")
                                                .addClass("key-text")
                                                .data('type', item.type)
                                                .data("text", item.text)
                                                .data('value', item.value || item.text)
                                                .text(item.text);
                                            if ('action' == item.type) {
                                                if (item.actionType == 'text') {
                                                    $li.data('key', getSearchKey(item.actionCode, item.cbData.default));
                                                } else {
                                                    $li.data('key', getSearchKey("", item.cbData.default));
                                                }
                                            }
                                            $keysHtml.append($li);
                                        })
                                        $(".keys-space").css("display", "flex");
                                        $(".keys-space").empty().append($keysHtml);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        html = $EMOTION.filterJingDong(html);
        return html;
    }

    function handleIFLYTEKBOTData(text, flag) {
        if (text) {
            if (typeof text == "string") {
                text = JSON.parse(text);
            }
            var ret = text.ret;
            if (ret == 0) {
                var outAction = text.outaction;
                if (outAction == 9) {
                    var outParams = text.outparams;
                    if (!flag) {
                        var toManual = outParams.toManual;
                        if (toManual == 1) {
                            $ROBOT.transferChat($config.queueId, '');
                            return;
                        }
                    }
                    var answer = outParams.answer;
                    if (answer == 1) {
                        var answerType = outParams.answerType;
                        switch (answerType) {
                            case '0': // 纯文本
                                html = outParams.prompt_text;
                                break;
                            case '1': //富文本, GET请求下来, 做展示
                                html = outParams.resourceUrl.replaceAll("\\\\", "").replace("\"<p>", "").replace("</p>\"", "");
                                break;
                            case '2': // 单图片
                                html = outParams.prompt_text;
                                break;
                            case '3': // 图文页面
                                html = outParams.resourceUrl.replaceAll("\\\\", "").replace("\"<p>", "").replace("</p>\"", "");
                                break;
                            default:
                                html = i18n.robot.noAnswer;
                        }
                    } else {
                        html = outParams.prompt_text || '';
                    }
                    if (outParams.prompt_guide)
                        html += '<br>' + (outParams.prompt_guide || '');
                    var moreResult = outParams.more_result;
                    if (moreResult && moreResult.length > 0) {

                        $.each(moreResult, function (i, result) {
                            html += '<span class="send-message" data-message="' + result.questionStd + '">' + result.questionStd + '</span>';
                        })
                    } else {
                        var extendParams = outParams.extendParams;
                        if (extendParams) { //该属性是针对于扩展内容的需要讯飞提供固定格式来进行解析
                            var robotConfigProperty = robotEngineConfig.property,
                                language = robotConfigProperty.language ? robotConfigProperty.language : "zh_CN",
                                key = 'record_' + language;
                            var record = extendParams[key];
                            if (record) {
                                var records = record.split("#");
                                if (records.length > 0) {
                                    if (outParams.prompt_guide) {
                                        html += '<br>' + outParams.prompt_guide;
                                    }
                                    $.each(records, function (i, result) {
                                        html += '<span class="send-message" data-message="' + result + '">' + result + '</span>';
                                    })
                                }
                            }
                            if (!flag) {
                                var chatBot = extendParams.chatBot;
                                if (chatBot == 'Cso') {
                                    $ROBOT.transferChat($config.queueId, '');
                                } else if (chatBot == 'Ending') {
                                    if (!flag) {
                                        if ($config.mobile) {
                                            $('#backBtn').click();
                                        } else {
                                            $('#back_div').click();
                                        }
                                    }
                                }
                            }
                        }
                    }

                } else {
                    html = i18n.robot.noAnswer;
                }
            } else if (ret == 5000 || ret == 5001 || ret == 5002 || ret == 5003 || ret == 5004) {
                if (!flag) {
                    if (!errorFlag) {
                        errorFlag = true
                        sendMsgWithSearchKeyBase('faqvote:sys_err', 'sys_err');
                    } else {
                        $ROBOT.transferChat($config.queueId, '');
                    }

                    return '';
                } else {
                    html = i18n.robot.noAnswer;
                }

            }

        }
        return html;
    }

    //容联云机器人
    function handleRLTEXTBOTData(text, flag) {
        var html = "";
        if (!text) {
            html = i18n.robot.error;
        } else {
            var text = JSON.stringify(text);
            if (typeof text == "string") {
                text = JSON.parse(text);
            }
            if (text.hasOwnProperty("turn_human") && text.turn_human) {
                // domToDialog(getNoticeForTransferMessage());
                $ROBOT.transferChat($config.queueId);
            } else {
                if (text.msg) {
                    //客户搞不定的逻辑说是：可以配置一个知识点，答案固定死为“转人工”，前端判断如果答案＝转人工
                    if ('转人工' == text.msg) {
                        html += text.turn_human_msg;
                        $ROBOT.transferChat($config.queueId);
                    } else {
                        html += text.msg;
                    }
                }
                if (text.relevant_list) {
                    $.each(text.relevant_list, function (i, simquestion) {
                        html += '<div class="send-message" data-message="' + simquestion + '">' + simquestion + '</div>';
                    })
                }
                if (text.StdQuestionList) {
                    $.each(text.StdQuestionList, function (j, stdquestion) {
                        html += '<div class="send-message" data-message="' + stdquestion + '">' + stdquestion + '</div>';
                    })
                }
                if (text.commonQuestionList) {
                    html += text.commonQuestionTip
                    $.each(text.commonQuestionList, function (j, commonQuestion) {
                        html += '<div class="send-message" data-message="' + commonQuestion + '">' + commonQuestion + '</div>';
                    })
                }
                if (text.common_questions) {
                    if (text.common_language)
                        html += text.common_language
                    html += text.common_questions
                    $.each(text.common_questions, function (j, commonQuestion) {
                        html += '<div class="send-message" data-message="' + commonQuestion + '">' + commonQuestion + '</div>';
                    })
                }
                if (text.bottom_menu && text.bottom_menu.length > 0) {
                    var $keysHtml = $('<ul>');
                    if (text.enable_bottom_common) {
                        var $li = $("<li>")
                            .addClass("key-text")
                            .data("text", '常见问题')
                            .data('type', 'text')
                            .data("key", '##常见问题##')
                            .data('value', '##常见问题##')
                            .text('常见问题');
                        $keysHtml.append($li);
                    }
                    $.each(text.bottom_menu, function (i, item) {
                        var type = 'text';
                        if (item.button_type === 2) type = 'link';
                        var $li = $("<li>")
                            .addClass("key-text")
                            .data('type', type)
                            .data("text", item.name)
                            .data("key", item.content)
                            .data('value', item.content || item.name)
                            .text(item.name);
                        $keysHtml.append($li);
                    })
                    $(".keys-space").css("display", "flex");
                    $(".keys-space").empty().append($keysHtml);
                }
                if (text.enable_is_useful) {
                    showStepAndLike = true;
                    likeButton = true;
                    stepButton = true;
                }

                if (html && text.log && (text.log.source === 1) && showStepAndLike) {
                    var log = text.log,
                        dom = 'data-oriquestion="' + log.ori_question + '"' +
                        ' data-question="' + log.std_question + '"' +
                        ' data-confidence="' + log.confidence + '"' +
                        ' data-distributechannel="' + log.distribute_channel_label + '"' +
                        ' data-channel="' + log.channel + '"' +
                        ' data-answer="' + text.msg + '"';
                    html += getLikeAndStepButtonHtml("", ROBOT_ID.RLTEXTBOT, dom);
                }
                if (text.common_questions_group) {
                    html = text.common_language;
                    html += '<div class="robot-content content">';
                    html += '<div class="img"><img class="thumb" src="' + text.common_questions_img + '"></div>';
                    html += '<div class="tabs">'
                    $.each(text.common_questions_group, function (i, cq) {
                        var active = i === 0 ? 'active' : '';
                        html += '<span data-id="' + i + '" class="tab-title ' + active + '">' + cq.name + '</span>';
                    })
                    html += '</div>'
                    html += '<div class="tabContent">'
                    $.each(text.common_questions_group, function (i, cq) {
                        var active = i === 0 ? 'active' : '';
                        var display = i === 0 ? 'display: block;' : 'display: none;';
                        html += '<span data-id="' + i + '" style="' + display + '" class="content ' + active + '" >';
                        $.each(cq.list, function (j, list) {
                            html += '<div class="send-message" data-message="' + list + '">' + list + '</div>';
                        })
                        html += '</span>'
                    })
                    html += '</div>'
                    html += '</div>';
                }
            }
        }
        return html;
    }

    //文本机器人
    function handleTEXTBOTData(text, flag) {
        var showStepAndLike = true;
        var html = "";
        if (!text) {
            html = i18n.robot.error;
        } else {
            try {
                var text = JSON.stringify(text);
                if (typeof text == "string") {
                    text = JSON.parse(text);
                }
            } catch (e) {
                return text;
            }

            var data = text.data;
            if (text.code === 0) {
                if (data) {
                    if (!flag && data.cmd && data.cmd == 'zrg') {
                        $ROBOT.transferChat($config.queueId);
                        return '';
                    }
                    var noAnswers = false,
                        noRecommend = false,
                        noMatchQuestion = !data.match_question;
                    var answers = data.answer;
                    if (answers) {
                        if (answers.length > 0) {
                            $.each(answers, function (i, answer) {
                                var aType = answer.type;
                                if ('text' === aType) {
                                    html += answer.text;
                                } else if ('image' === aType) {
                                    html += '<img src="' + answer.url + '" alt="' + answer.name + '"/>'
                                } else if ('audio' === aType) {
                                    html += '<div class="message-voice" data-from="robot" data-url="' + answer.url + '" data-length="' + answer.duration + '"></div>'
                                } else if ('video' === aType) {
                                    html += '<video src="' + answer.url + '" controls="controls"></video>'
                                } else if ('html' === aType) {
                                    html += answer.text;
                                }
                            })
                        } else {
                            noAnswers = true;
                            showStepAndLike = false;
                            if (robotEngineConfig.noAnswerMessage)
                                html = robotEngineConfig.noAnswerMessage;
                            else
                                html = i18n.robot.noAnswer;
                        }
                        if (data.recommend && data.recommend.length > 0) {
                            $.each(data.recommend, function (i, rd) {
                                if (i == 0) {
                                    if (typeof rd === 'string') {
                                        html += '<p class="que-title">' + (robotEngineConfig.doYouWantMessage ? robotEngineConfig.doYouWantMessage : "不太确定您的意思哦，请问您想问的是？") + '</p>';
                                    } else {
                                        html += '<p class="que-title">' + (robotEngineConfig.associatedMessage ? robotEngineConfig.associatedMessage : "您是否想问:") + '</p>';
                                    }
                                }
                                if (typeof rd === 'string') {
                                    html += '<div class="send-message" data-message="' + rd + '">' + rd + '</div>';
                                } else {
                                    html += '<div class="send-message" data-message="' + rd.question + '">' + rd.question + '</div>';
                                }
                            })
                        } else {
                            noRecommend = true;
                        }
                        if (!flag && noAnswers && noRecommend && noMatchQuestion) {
                            robotCodeReject++;
                            var noAnswerTimes = robotEngineConfig.noAnswerTimes || 3;
                            if (robotCodeReject >= noAnswerTimes) {
                                robotCodeReject = 0;
                                html = getNoticeForTransferMessage();
                            }
                        } else {
                            robotCodeReject = 0;
                        }
                    }
                }
            } else {
                html += text.msg || i18n.robot.error;
            }
        }
        if (!flag && html && showStepAndLike) {
            var dom = 'data-messageid="' + data.msg_id + '"';
            html += getLikeAndStepButtonHtml("", ROBOT_ID.TEXTBOT, dom);
        }
        return html;
    }


    //jh机器人
    function handleCOMMUNICATIONSBOTData(text, flag) {
        var html = "";
        if (!text) {
            html = i18n.robot.error;
        } else {
            try {
                var text = JSON.stringify(text);
                if (typeof text == "string") {
                    text = JSON.parse(text);
                }
            } catch (e) {
                return text;
            }

            var type = text.type;
            if (type == 101) {
                if (text.content) {
                    $ROBOT.transferChat($config.queueId, text.content);
                    return '';
                }
            } else {
                if (text.commands) {
                    var commands = text.commands;
                    var name = commands.name;
                    if (name === 'imgtxtmsg') {
                        var xmlDoc = $.parseXML('<root>' + text.content + '</root>'),
                            $xml = $(xmlDoc),
                            $item = $xml.find("item");
                        html += domImageText.domImageTextHomeAppend();
                        $.each($item, function (i, item) {
                            var isFirst = false;
                            if (i == 0) isFirst = true;
                            html += domImageText.domImageText(wrapCDATA($(item).find('Title')[0].textContent),
                                wrapCDATA($(item).find('Description')[0].textContent),
                                wrapCDATA($(item).find('PicUrl')[0].textContent),
                                wrapCDATA($(item).find('Url')[0].textContent), isFirst)
                        })
                        html += domImageText.domImageTextEndAppend();
                    }
                } else {
                    if (text.content) {
                        html = wrapLink(text.content);
                    }
                }
            }
            if (text.relatedQuestions) {
                var relatedQuestions = text.relatedQuestions;
                if (typeof text.relatedQuestions == 'string') {
                    relatedQuestions = relatedQuestions.split(',');
                }
                $.each(relatedQuestions, function (i, relatedQuestion) {
                    html += '<div class="send-message" data-message="' + relatedQuestion + '">' + relatedQuestion + '</div>';
                })
            }
        }
        // if (!flag && html) {
        //     var dom = 'data-messageid="' + data.msg_id + '"';
        //     html += getLikeAndStepButtonHtml("", ROBOT_ID.COMMUNICATIONSBOT, dom);
        // }
        return html;
    }


    //文本机器人
    function handleDZBOTData(text, flag) {
        var html = '';
        if (text.code === '10000') {
            var data = text.data;
            if (data.dmResSingleAnswerList) {
                $.each(data.dmResSingleAnswerList, function (i, dmResSingleAnswer) {
                    html += dmResSingleAnswer.answerData;
                })
            }
            if (data.dmResGuideAnswer) {
                var dmResGuideAnswer = data.dmResGuideAnswer;
                if (dmResGuideAnswer.dmResSpecialRecommend) {
                    var dmResSpecialRecommend = dmResGuideAnswer.dmResSpecialRecommend;
                    if (dmResSpecialRecommend.specialTip) {
                        html += dmResSpecialRecommend.specialTip;
                    }
                    if (dmResSpecialRecommend.recommendAnswers) {
                        $.each(dmResSpecialRecommend.recommendAnswers, function (i, recommendAnswer) {
                            html += '<div class="send-message" data-message="' + recommendAnswer.standardQuestion + '">' + recommendAnswer.standardQuestion + '</div>';
                        })
                    }
                }
            }

            if (data.dmResPictureGuid && data.dmResPictureGuid.pictureRecommendAnswerList) {
                var $quickcardHtml = $("<div>").addClass("quickcard"),
                    $content = $("<div>").addClass("content"),
                    $ul = $("<div>").addClass("ul");
                $.each(data.dmResPictureGuid.pictureRecommendAnswerList, function (j, item) {
                    var $li = $("<div>").addClass("li").addClass('key-text')
                        .data("text", item.title)
                        .data("value", item.title);
                    $li.data('type', item.recommendType);
                    if (7 == item.recommendType) {
                        $li.data('key', getSearchKey("", item.cbData.default));
                    } else if (8 === item.recommendType) {
                        $li.data('key', item.title);
                    }
                    var $item = $("<div>").addClass("item"),
                        $topImg = $("<div>").addClass("topImg").append($("<img>").addClass('avatar').attr('src', fileUrl + item.picture)),
                        $font = $("<div>").addClass("font").text(item.title);
                    $item.append($topImg).append($font);
                    $li.append($item);
                    $ul.append($li);
                })
                $quickcardHtml.html($content.html($ul));
                domImageText.appendDom($quickcardHtml);
            }
        }

        // if (!flag && html) {
        //     var dom = 'data-messageid="' + data.msg_id + '"';
        //     html += getLikeAndStepButtonHtml("", ROBOT_ID.COMMUNICATIONSBOT, dom);
        // }
        return html;
    }


    //百度机器人
    function handleBAIDUBOTData(text, flag) {
        var html = '';
        if (text.code === 200) {
            var data = text.data;
            if (data.welcome) html += data.welcome;
            if (data.qaRecommendTitle) html += "\n\n" + data.qaRecommendTitle;
            var qaRecommend = data.qaRecommend;
            if (qaRecommend) {
                $.each(qaRecommend, function (index) {
                    html += '<div class="send-message" data-message="' + qaRecommend[index] + '">' + qaRecommend[index] + '</div>';
                })
            }
            if (data.answer) {
                var answerContents = data.answer.answerContents;
                if (answerContents) {
                    $.each(answerContents, function (index) {
                        var answerContent = answerContents[index],
                            type = answerContent.type;
                        switch (type) {
                            case 3:
                                html += answerContent.text;
                                break
                            case 8:
                                html += answerContent.title;
                                var list = answerContent.list;
                                $.each(list, function (i) {
                                    var question = list[i];
                                    html += '<div class="send-message" data-message="' + question + '">' + question + '</div>';
                                })
                                break;
                            default:
                                html += answerContent.text;
                                break
                        }
                    })
                }
            }

            if (data.actions && data.actions.length > 0) {
                $.each(data.actions, function (index) {
                    var item = data.actions[index];
                    if (item.indexOf('zrg') > -1) {
                        $ROBOT.transferChat($config.queueId, item);
                    }
                })
            }
        }
        return html;
    }


    //百度机器人
    function handleIWENCAIBOTData(text, flag) {
        var html = '';
        if (text.status_code === 0) {
            if (text.answer) {
                var answerContents = text.answer;
                if (answerContents) {
                    $.each(answerContents, function (index) {
                        var answerContent = answerContents[index],
                            textAnswer = answerContent.text_answer,
                            voiceTxt = answerContent.voice_txt,
                            sugTitle = answerContent.sug_title,
                            sugArr = answerContent.sugArr,
                            sugs = answerContent.sugs;
                        var txts = answerContent.txt;
                        $.each(txts, function (j) {
                            var txt = txts[j];
                            if (txt.content) {
                                html += txt.content.answer;
                            }
                        })
                        if (sugs && sugs.length > 0) {
                            html += text.sug_title || '';
                            $.each(sugs, function (i) {
                                var sug = sugs[i];
                                $.each(sug.sug, function (m) {
                                    var sugm = sug.sug[m];
                                    html += '<div class="send-message" data-message="' + sugm.click_sug + '">' + sugm.display_sug + '</div>';
                                })

                            })
                        } else if (sugArr && sugArr.length > 0) {
                            $.each(sugArr, function (i) {
                                var sugArr = answerContent.sugArr[i];
                                html += sugArr.sug_title ? ('<p>' + sugArr.sug_title || '' + '</p>') : '';
                                $.each(sugArr.sugs, function (j) {
                                    var sugs = answerContent.sugs[j];
                                    $.each(sugs.sug, function (m) {
                                        var sug = sugs.sug[m];
                                        html += '<div class="send-message" data-message="' + sug.click_sug + '">' + sug.display_sug + '</div>';
                                    })

                                })
                            })
                        }
                    })
                }
                var es = text.es;
                if (es) {
                    var connectType = es.connect_type;
                    if (connectType === 1) {
                        $ROBOT.transferChat($config.queueId, es.expert_type);
                    }
                }
            }
            // var recommend = text.recommend;
            // if (recommend) {
            //     html += recommend.sug_title || '';
            //     $.each(recommend.questions, function (index) {
            //         html += '<div class="send-message" data-message="' + recommend.questions[index] + '">' + recommend.questions[index] + '</div>';
            //     })
            // }
        }

        if (!flag && html) {
            var dom = ' data-questionid="' + (text.question_id || '') + '" data-topic="' + (text.question || '') + '"';
            html += getLikeAndStepButtonHtml("", ROBOT_ID.IWENCAIBOT, dom);
        }
        if (!html) {
            html = i18n.robot.error;
        }
        return html;
    }

    var wrapURL = function (str, options = {}) {
        if (options.nowrap) {
            return str;
        }
        try {
            if ($(str).length > 0) {
                return str;
            }
        } catch (e) {}
        // 原来的正则必须包含http://或者https://     /(http:|https:)\/\/[A-Za-z0-9\._\?%&+\-=/#]*/gi
        // /(((https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www\..|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)(?::(\d+))?((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\+~%\/.\w-_\?=&;%@]*))?)((?!http|([u4e00-u9fa5])*).)*/g
        let matchURLs = $('<div>').append(str).text().match(/(https?:\/\/)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/g);
        if (matchURLs) {
            // 去重
            matchURLs = matchURLs.filter((item, index, self) => {
                return self.indexOf(item) === index;
            });
            // 按长度排序，长的排在前面，这样长的就可以先替换，避免短的先替换时候长的里面刚好有短的部分，造成替换错误
            matchURLs.sort((a, b) => {
                return b.length - a.length;
            });
            var replaceUrls = [];
            matchURLs.forEach(url => {
                //经过text()方法后，字符串中的&amp;会变成& 这里要判断一下，如果存在这种情况，就要再replace一次
                let parsedUrl = url.replace(/&/g, '&amp;').replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
                str = str.replace(new RegExp(parsedUrl, "g"), function (matchStr) {
                    let url = matchStr;
                    if (!matchStr.startsWith('http://') && !matchStr.startsWith('https://')) {
                        url = 'http://' + matchStr;
                    }
                    // 如果设置了黑白名单，则要判断域名是否安全
                    if (options.whiteList || options.blackList) {
                        try {
                            let u = new URL(url);
                            let hostname = u.hostname;
                            if (options.whiteList && options.whiteList.length > 0) {
                                if (!options.whiteList.find(w => {
                                        return w === hostname
                                    })) {
                                    return matchStr
                                }
                            } else if (options.blackList && options.blackList.length > 0) {
                                if (options.blackList.find(w => {
                                        return w === hostname
                                    })) {
                                    return matchStr
                                }
                            }
                        } catch (e) {
                            return matchStr
                        }
                    }

                    let origin = '<a target="_blank" href="' + url + '" class="chat-wrap">' + matchStr + '</a>';
                    let digest = $.md5(origin);
                    replaceUrls.push({
                        origin,
                        digest
                    });
                    return digest;
                });
            });
            // 通过对需要替换内容做md5，避免轮训替换时候，之前替换后的内容里又匹配到了后面需要替换的内容
            replaceUrls.forEach(rurl => {
                str = str.replace(rurl.digest, rurl.origin);
            })
        }
        return str;
    };

    function getData(postTime) {
        var now = new Date(postTime),
            seconds = now.getSeconds(),
            minutes = now.getMinutes();
        if (parseInt(seconds) < 10) seconds = '0' + now.getSeconds();
        if (parseInt(minutes) < 10) minutes = '0' + now.getMinutes();
        return now.getHours() + ":" + minutes + ":" + seconds;
    };

    var ROBOT_ID = {
        "KMBOT": "BOT000",
        "YIBOT": "BOT001",
        "XIAOIBOT": "BOT002",
        "XIAODUO": "BOT003",
        "SOBOT": "BOT004",
        "ELITEBOT": "BOT005",
        "EBOSSBOT": "BOT006",
        "ELIEAI": "BOT007",
        "ZTEROBOT": "BOT008",
        "SINOROBOT": "BOT009",
        "EMOTIBOT": "BOT010",
        "YUNWBOT": "BOT011",
        "ECHATBOT": "BOT012",
        "DKNTBOT": "BOT013",
        "YANXIBOT": "BOT014",
        "IFLYTEKBOT": "BOT015",
        "GUANGDABOT": "BOT016",
        "RLTEXTBOT": "BOT017",
        "TEXTBOT": "BOT018",
        "COMMUNICATIONSBOT": "BOT019",
        "DZBOT": "BOT020",
        "BAIDUBOT": "BOT021",
        "IWENCAIBOT": "BOT022"
    };

    var ROBOT_FROM_TYPE = {
        "0": "BOT000",
        "1": "BOT001",
        "2": "BOT002",
        "3": "BOT003",
        "4": "BOT004",
        "5": "BOT005",
        "6": "BOT006",
        "7": "BOT007",
        "8": "BOT008",
        "9": "BOT009",
        "10": "BOT010",
        "11": "BOT011",
        "12": "BOT012",
        "13": "BOT013",
        "14": "BOT014",
        "15": "BOT015",
        "16": "BOT016",
        "17": "BOT017",
        "18": "BOT018",
        "19": "BOT019",
        "20": "BOT020",
        "21": "BOT021",
        "22": "BOT022"
    };

    var domAnswerTitleAppend = function (title, question, answer, i, messageId, appendDom, hideListNum) {
        var question = title || question,
            text = question;
        if (!hideListNum)
            text = (i + 1) + '. ' + text;
        return '<div class="each-message">' +
            '<div class="message-title" ' + appendDom + ' data-messageid = "' + messageId + '" data-title = "' + title + '" data-question = \'' + question + '\' >' + title + '</div>' +
            '<div class="message-preview" style="display: none">' + answer + '</div>' +
            '</div>';
    };

    function wrapLink(answer, robotType, isHis, messageId, robotId, feedBackResult) {
        robotType = robotType || '', isHis = isHis || false, messageId = messageId || '', robotId = robotId || '', feedBackResult = feedBackResult || '';
        if (answer) {
            var extraDom = '';
            if (robotType) {
                extraDom = 'data-extra="' + robotType + '"';
            }
            var reg1 = new RegExp(/\[link(.*?)url="(.*?)"](.*?)\[\/link]/g);
            while (reg1.test(answer)) {
                answer = answer.replace(reg1, '<a ' + extraDom + ' href="$2" target="_blank">$3</a>');
            }
            var reg2 = new RegExp(/\[link(.*?)submit="(.*?)"](.*?)\[\/link]/g);
            while (reg2.test(answer)) {
                answer = answer.replace(reg2, '<a ' + extraDom + ' class="send-message" data-message="$2">$3</a>');
            }
            var reg3 = new RegExp(/\[link](.*?)\[\/link]/g);
            while (reg3.test(answer)) {
                answer = answer.replace(reg3, '<a ' + extraDom + ' class="send-message" data-message="$1">$1</a>');
            }
            var reg4 = new RegExp(/\[link(.*?)post="(.*?)"](.*?)\[\/link]/g);
            var rateFlag = false;
            if (reg4.test(answer)) {
                var revokeDom = '';
                if (!isHis) {
                    revokeDom = ' data-revoke="' + messageId + '" ';
                }
                answer = answer.replace(reg4, function (a, k, v, b, c) {
                    console.log('messageId is [%s], a ---  %s ,\nk ---  %s ,\nv ---  %s ,\nc ---  %s, \nb ---  %s', messageId, a, k, v, c, b);
                    var active = '';
                    if (v.indexOf(' 1 ') > 0) {
                        var feedback = true,
                            likesStateClass = ''; //状态存在三种不可操作，已经操作， 可操作
                        if (!isHis) {
                            if (feedBackResult) {
                                feedback = false
                                likesStateClass = 'operabled'; //已经操作
                            } else {
                                likesStateClass = 'operable'; //可操作
                            }
                        } else {
                            feedback = false
                            likesStateClass = 'inoperable'; //不可操作
                        }
                        if (feedBackResult == 1) {
                            active = 'active';
                        }
                        return '<div class="rate-message likes ' + likesStateClass + '" data-feedback="' + feedback + '"><div>' +
                            '<div class="like" ' + extraDom + ' data-msg="' + b + '" data-search="' + v + '" data-id="' + messageId + '" data-robotId="' + robotId + '" ' + ' data-post="1"' + revokeDom + '>' +
                            '<i class="' + active + '"></i>' + b +
                            '</div>';
                    } else if (v.indexOf(' 2 ') > 0) {
                        var rateExtendFlag = _dissatisfactionReasons ? true : false;
                        rateFlag = true;
                        if (feedBackResult == 2) {
                            active = 'active';
                        }
                        var stepDom = '<div class="step" ' + extraDom + ' data-reason="' + rateExtendFlag + '" data-msg="' + b + '" data-search="' + v + '" data-id="' + messageId + '" data-robotId="' + robotId + '" ' + ' data-post="2"' + revokeDom + '>' +
                            '<i class="' + active + '"></i>' + b +
                            '</div>' +
                            '</div>';

                        if (rateExtendFlag) {
                            stepDom += '<div class="step-extend hide">';
                            stepDom += '<div class="step-reason">';
                            stepDom += '<div class="reason-title">' + i18n.robot.stepReason + '</div>';
                            stepDom += '<div class="reason-main">';
                            $.each(JSON.parse(_dissatisfactionReasons), function (i, r) {
                                stepDom += '<div class="reason-li step-li" data-reason="false" ' + extraDom + ' data-msg="' + b + '" data-search="' + v.replace('{4}', r.REASON_DETAIL) + '" data-id="' + messageId + '" data-robotId="' + robotId + '" ' + ' data-post="2"' + revokeDom + ' data-code="' + r.REASON_CODE + '" data-detail="' + r.REASON_DETAIL + '">' + r.REASON_DETAIL + '</div>';
                            })
                            stepDom += '</div>';
                            stepDom += '</div>';
                            stepDom += '</div>';
                        }
                        stepDom += '</div>';

                        return stepDom;
                    } else {
                        if (isHis)
                            return '<a ' + extraDom + ' class="send-message">' + b + '</a>';
                        else
                            return '<a ' + extraDom + ' class="send-message" data-key="' + v + '" data-message="' + b + '">' + b + '</a>';
                    }
                });
            }

            var reg5 = new RegExp(/\[link(.*?)submit="(.*?)"]/g);
            while (reg5.test(answer)) {
                answer = answer.replace(reg5, '<a ' + extraDom + ' class="send-message" data-message="$2">$2</a>');
            }
            var reg6 = new RegExp(/\[link(.*?)cmd="(.*?)"](.*?)\[\/link]/g);
            while (reg6.test(answer)) {
                answer = answer.replace(reg6, '<a ' + extraDom + ' class="send-message" data-cmd="$2">$3</a>');
            }
        }
        return answer
    };

    function wrapATag(str) {
        if (!$config.mobile) {
            var reg = new RegExp(/<a target="_blank" href="([^\]]*)\">([^\]]*)<\/a>/i);
            while (reg.test(str)) {
                str = str.replace(reg, '<a target=\\\"_blank\\\" href=\\\"$1\\\">$2</a>');
            }
        }
        return str;
    };

    function wrapATagAddTarget(str) {
        var reg = new RegExp(/<a href=([^\]]*)\>([^\]]*)<\/a>/i);
        while (reg.test(str)) {
            str = str.replace(reg, "<a target=\\\"_blank\\\" href=$1>$2</a>");
        }
        return str;
    };

    function wrapCDDATA(str) {
        var reg = new RegExp(/<\!\[CDATA\[([\S\s].*)\]\]>/i);
        while (reg.test(str)) {
            str = str.replace(reg, '$1').replace('<![CDATA[]]>', '');
        }
        return str;
    };

    function wrapClickMessage(str) {
        return str.replaceAll(/(.*?)【(.*?)】(.*?)/g, '$1<a class="send-message" data-message=\"$2\">$2</a>')
    };

    function delayNotice() {
        if (!$config.mobile) {
            $("#waitingForAcceptInChatView").show(10).delay(5500);
        }
    };

    var domImageText = {
        domImageTextHomeAppend: function () {
            return '<ul class="tb-view">';
        },

        domImageTextEndAppend: function () {
            return '</ul>';
        },

        domImageText: function (title, description, picUrl, url, isFirst) {
            var html = "";
            if (isFirst) {
                html += '<li class="tb-cell tb-cell_first"><a href="' + url + '" target="_blank">' +
                    '<div class="first-img">' +
                    '<img src="' + picUrl + '" alt="' + title + '" style="max-width: 300px; max-height: 300px;" class="tb-img fl" />' +
                    '</div>';
            } else {
                html += '<li class="tb-cell"><a href="' + url + '" target="_blank">' +
                    '<img src="' + picUrl + '" alt="' + title + '" style="max-width: 300px; max-height: 300px;" class="tb-img fl" />';
            }
            html += '<div class="tb-body">';
            html += '<p class="tb-title">' + title + '</p>';
            if (description) {
                html += '<p class="tb-content">' + description + '</p>';
            }
            html += '</div>';
            html += '</a></li>';
            return html;
        },
        setNotices: function (str) {
            if ($config.mobile) {
                $("#clientResponseDiv").append("<p class=\"messageTips\"><em>" + msg + "</em></p>");
            } else {
                $("#waitingForAcceptInChatView").html($F.formatTopNotice(str));
            }
        },
        appendDom: function (dom) {
            if ($config.mobile) {
                $("#clientResponseDiv").append(dom);
            } else {
                $F.appendTextToDiv("clientResponseDiv", dom);
            }
        }
    };

    var messageHtml = {
        "KMBOT": function (text, flag) {
            return handleKMBOTData(text, flag);
        },

        "YIBOT": function (text, flag) {
            return handleYibotData(text, flag);
        },

        "XIAOIBOT": function (messageId, text, flag) {
            return handleXiaoIbotData(messageId, text, flag);
        },
        "XIAODUOBOT": function (text, flag) {
            return handleXiaoDuobotData(text, flag);
        },
        "SOBOT": function (text, flag) {
            return handleSobotData(text, flag);
        },
        "ELITEBOT": function (text, flag) {
            return handleElitebotData(text, flag);
        },
        "EBOSSKMBOT": function (text, flag) {
            return handleEbossKMbotData(text, flag);
        },
        "ELITEAIBOT": function (text, flag) {
            return handleEliteAIbotData(text, flag);
        },
        "ZTEROBOT": function (text, flag) {
            return handleZTEROBOTData(text, flag);
        },
        "SINOROBOT": function (text, flag) {
            return handleSinoROBOTData(text, flag);
        },
        "EMOTIBOT": function (text, flag) {
            return handleEemotiBOTData(text, flag);
        },
        "YUNWBOT": function (text, flag) {
            return handleYunwBOTData(text, flag);
        },
        "ECHATBOT": function (text, flag) {
            return handleECHATBOTData(text, flag);
        },
        "DKNTBOT": function (text, flag) {
            return handleDKNTBOTData(text, flag);
        },
        "YANXIBOT": function (text, flag) {
            return handleYANXIBOTData(text, flag);
        },
        "IFLYTEKBOT": function (text, flag) {
            return handleIFLYTEKBOTData(text, flag);
        },
        "GUANGDABOT": function (text, flag) {
            return handleGUANGDABOTData(text, flag);
        },
        "RLTEXTBOT": function (text, flag) {
            return handleRLTEXTBOTData(text, flag);
        },
        "TEXTBOT": function (text, flag) {
            return handleTEXTBOTData(text, flag);
        },
        "COMMUNICATIONSBOT": function (text, flag) {
            return handleCOMMUNICATIONSBOTData(text, flag);
        },
        "DZBOT": function (text, flag) {
            return handleDZBOTData(text, flag);
        },
        "BAIDUBOT": function (text, flag) {
            return handleBAIDUBOTData(text, flag);
        },
        "WENCAIBOT": function (text, flag) {
            return handleIWENCAIBOTData(text, flag);
        }
    }

    window.$ROBOT = {
        init: function (robotEngine) {
            try {
                if (robotEngine) {
                    hasRobot = true;
                    if (typeof robotEngine == 'string') {
                        robotEngineConfig = JSON.parse(robotEngine);
                    } else {
                        robotEngineConfig = robotEngine;
                    }
                    robotId = ROBOT_FROM_TYPE[robotEngineConfig.type];
                    if (robotEngineConfig.property) {
                        var robotConfigProperty = robotEngineConfig.property;
                        if (robotConfigProperty.feedbackTips) {
                            feedbackTips = robotConfigProperty.feedbackTips;
                        }
                        if (robotConfigProperty.transferName) {
                            transferName = robotConfigProperty.transferName;
                        }
                        if (robotConfigProperty.transferTips) {
                            transferTips = robotConfigProperty.transferTips;
                        }
                        if (robotConfigProperty.hasOwnProperty('allowRate')) {
                            allowRateForClientCloseSession = robotConfigProperty.allowRate;
                        }
                        var clickHtml = getTransferClickHtml();
                        if (transferTips.indexOf('{0}') > -1) {
                            transferTips = transferTips.replace('{0}', clickHtml);
                        }
                        if (robotConfigProperty.sessionRound) {
                            sessionRound = robotConfigProperty.sessionRound;
                        }
                        if (robotConfigProperty.sessionRoundTips) {
                            sessionRoundTips = robotConfigProperty.sessionRoundTips;
                        }
                        if (robotConfigProperty.isHiddenTransferHtml) {
                            isHiddenTransferHtml = robotConfigProperty.isHiddenTransferHtml;
                        }
                        if (robotConfigProperty.version) {
                            robotVersion = robotConfigProperty.version
                        }
                        if (robotConfigProperty.hasOwnProperty("showDialog")) {
                            transferNoticeShowDialog = robotConfigProperty.showDialog
                        }
                        if (robotConfigProperty.wework) {
                            isWework = robotConfigProperty.wework
                        }
                        if (robotConfigProperty.likeButton) {
                            likeButton = robotConfigProperty.likeButton;
                            if (likeButton) {
                                if (robotConfigProperty.likeButtonName) {
                                    likeButtonName = robotConfigProperty.likeButtonName;
                                }
                            }
                        }
                        if (robotConfigProperty.stepButton) {
                            stepButton = robotConfigProperty.stepButton;
                            if (stepButton) {
                                if (robotConfigProperty.stepButtonName) {
                                    stepButtonName = robotConfigProperty.stepButtonName;
                                }
                            }
                            if (robotConfigProperty.afterStepToShowTransferButton) {
                                afterStepToShowTransferButton = robotConfigProperty.afterStepToShowTransferButton;
                            }
                        }
                        if (robotConfigProperty.transeferButton) {
                            transferButton = robotConfigProperty.transeferButton;
                        }
                        if (robotConfigProperty.ordersPageSize) {
                            ordersPageSize = robotConfigProperty.ordersPageSize;
                        }
                        if (robotConfigProperty.orderHrefType) {
                            orderHrefType = robotConfigProperty.orderHrefType;
                        }
                        if (robotConfigProperty.fileUrl) {
                            fileUrl = robotConfigProperty.fileUrl;
                        }
                        if (robotConfigProperty.mobileVerify) {
                            mobileVerify = robotConfigProperty.mobileVerify;
                        }
                        if (robotConfigProperty.contentMaxHeight) {
                            contentMaxHeight = robotConfigProperty.contentMaxHeight;
                            $(".custom_service.message-slim").css("max-height", contentMaxHeight + "px")
                        }
                        if (robotConfigProperty.cityOptions) {
                            showCityButton = true;
                            $CITY.show(robotConfigProperty.cityOptions);
                        }
                        if (robotConfigProperty.navBar) {
                            showNavBarButton = true;
                        }

                        if (robotConfigProperty.rateButton) {
                            showRateButton = true;
                        }

                        if (robotConfigProperty.robotTools) {
                            robotTools = true;
                        }

                        if (robotConfigProperty.qrStayTime) {
                            questionRecommendationStayTime = robotConfigProperty.qrStayTime;
                        }
                        if (robotConfigProperty.hasOwnProperty("compressionImage"))
                            compressionImage = robotConfigProperty.compressionImage;
                        /**
                         * 配置手机验证隐私协议是否添加路径
                         */
                        if (robotConfigProperty.mobileVerifyPath) {
                            mobileVerifyPath = robotConfigProperty.mobileVerifyPath;
                        }
                        /**
                         * 配置是不是只对机器人返回的结果内容进行隐藏不隐藏相关问题
                         */
                        if (robotConfigProperty.slimContent) {
                            slimContent = robotConfigProperty.slimContent;
                        }
                        /**
                         * 配置历史是否展示为你查看的问题如下
                         */
                        if (robotConfigProperty.multipleHistories) {
                            multipleHistories = robotConfigProperty.multipleHistories;
                        }
                        /**
                         * 机器人列表的显示方式
                         */
                        if (robotConfigProperty.robotListView) {
                            robotListView = robotConfigProperty.robotListView;
                        }

                    }
                }
            } catch (e) {
                robotLog(e.message, 'on robot init');
            }
        },
        getRobotVersion: function () {
            return robotVersion;
        },

        isShowCityButton: function () {
            return showCityButton;
        },

        isShowNavBarButton: function () {
            return showNavBarButton;
        },

        isShowRateButton: function () {
            return showRateButton;
        },

        isShowRobotToolsButton: function () {
            return robotTools;
        },

        getStayTimeForQuestionRecommendation: function () {
            return questionRecommendationStayTime;
        },

        isPocVersion: function () {
            return robotVersion === 'poc';
        },

        transferingChange: function (flag) {
            $(".timeWait").hide();
            _transfering = flag;
            if ($config.queue.transferingNotInput) {
                if (flag) {
                    if ($config.mobile) {
                        $("#clientResponseDiv").append("<p class=\"messageTips\" id=\"timer\"><span></span></p>")
                        this.timeWait(function (numberMText, numberTimeText) {
                            $("#timer").html('<span>' + i18n.common.waitingTime + ':&nbsp;&nbsp;' + numberMText + '：' + numberTimeText + '</span>');
                        });
                    } else {
                        $("#talkBox").append("<div class=\"no-bg no-yel\" id=\"timer\"><div class=\"notice\"><span></span></div></div>")
                        this.timeWait(function (numberMText, numberTimeText) {
                            $("#timer .notice").html('<span>' + i18n.common.waitingTime + ':&nbsp;&nbsp;' + numberMText + '：' + numberTimeText + '</span>');
                        });
                    }
                } else {
                    $("#timer").remove();
                    clearInterval(timerNum)
                }
                if ($config.mobile) {
                    $('#clientMessageBox').attr('contenteditable', !flag)
                } else {
                    chatEditor.readonly(flag);
                }
            } else {
                if (!flag) {
                    $("#timer").remove();
                    clearInterval(timerNum)
                }
            }
        },

        // 等待时长问题
        timeWait: function (callback) {
            var tips = ''
            var numberTime = 0;
            var numberM = 0;
            var numberMText = '';
            var numberTimeText = '';

            function PrefixInteger(num, m) {
                return (Array(m).join(0) + num).slice(-m);
            }

            if ($config.mobile) {
                timerNum = setInterval(function () {
                    numberTime++;
                    if (numberTime >= 60) {
                        numberM++
                        numberTime = 0
                    }
                    numberMText = PrefixInteger(numberM, 2);
                    numberTimeText = PrefixInteger(numberTime, 2);
                    if (numberTime >= 2 || numberM > 0) {
                        $('#orderInQueue span').remove()
                    }
                    callback(numberMText, numberTimeText)
                }, 1000);
            } else {
                timerNum = setInterval(function () {
                    numberTime++;
                    if (numberTime >= 60) {
                        numberM++;
                        numberTime = 0
                    }
                    numberMText = PrefixInteger(numberM, 2);
                    numberTimeText = PrefixInteger(numberTime, 2)
                    callback(numberMText, numberTimeText);
                }, 1000);
            }

        },

        isuniqloVersion: function () {
            return 'uniqlo' == robotVersion;
        },

        dealData: function (content, userId, flag, messageId, feedBackResult) {
            messageId = messageId || '', feedBackResult = feedBackResult || '';
            var msgText = '';
            var html = "";
            if (!content) return i18n.robot.error;
            try {
                if (typeof content != 'object') {
                    content = content.replaceAll('\r\n', '<br>').replaceAll('\n\r', '<br>').replaceAll('\r', '<br>').replaceAll('\n', '<br>').replaceAll('\b', ' ');
                    content = wrapATag(content);
                    try {
                        var isJson = JSON.parse(content);
                        if (typeof isJson == 'object' && isJson) {
                            content = isJson;
                        }
                    } catch (e) {
                        return content;
                    }
                }
                if (content.errorCode === 'zrg' && !flag) {
                    $ROBOT.transferChat($config.queueId);
                }
                if (userId == ROBOT_ID.KMBOT) {
                    msgText = messageHtml.KMBOT(content, flag);
                } else if (userId == ROBOT_ID.YIBOT) {
                    msgText = messageHtml.YIOBT(content, flag);
                } else if (userId == ROBOT_ID.XIAOIBOT) {
                    if ('uniqlo' == robotVersion) {
                        msgText = messageHtml.XIAOIBOT(messageId, content, flag);
                        msgText = wrapLink(msgText, content.robotType, flag, messageId, ROBOT_ID.XIAOIBOT, feedBackResult);
                    } else {
                        msgText = messageHtml.XIAOIBOT(messageId, content, flag);
                        msgText = wrapLink(msgText);
                    }
                    if (msgText) {
                        msgText = msgText.replaceAll('\\[link]', '').replaceAll('\\[\/link]', '');
                    }

                } else if (userId == ROBOT_ID.XIAODUO) {
                    msgText = messageHtml.XIAODUO(content, flag);
                } else if (userId == ROBOT_ID.SOBOT) {
                    msgText = messageHtml.SOBOT(content, flag);
                } else if (userId == ROBOT_ID.ELITEBOT) {
                    msgText = messageHtml.ELITEBOT(content, flag);
                } else if (userId == ROBOT_ID.EBOSSBOT) {
                    msgText = messageHtml.EBOSSKMBOT(content, flag);
                } else if (userId == ROBOT_ID.ELIEAI) {
                    msgText = messageHtml.ELITEAIBOT(content, flag);
                } else if (userId == ROBOT_ID.ZTEROBOT) {
                    msgText = messageHtml.ZTEROBOT(content, flag);
                } else if (userId == ROBOT_ID.SINOROBOT) {
                    msgText = messageHtml.SINOROBOT(content, flag);
                } else if (userId == ROBOT_ID.EMOTIBOT) {
                    msgText = messageHtml.EMOTIBOT(content, flag);
                } else if (userId == ROBOT_ID.YUNWBOT) {
                    msgText = messageHtml.YUNWBOT(content, flag);
                } else if (userId == ROBOT_ID.ECHATBOT) {
                    msgText = messageHtml.ECHATBOT(content, flag);
                } else if (userId == ROBOT_ID.DKNTBOT) {
                    msgText = messageHtml.DKNTBOT(content, flag);
                } else if (userId == ROBOT_ID.YANXIBOT) {
                    msgText = messageHtml.YANXIBOT(content, flag);
                } else if (userId == ROBOT_ID.IFLYTEKBOT) {
                    msgText = messageHtml.IFLYTEK(content, flag);
                    msgText = wrapLink(msgText);
                } else if (userId == ROBOT_ID.GUANGDABOT) {
                    msgText = messageHtml.GUANGDABOT(content, flag);
                    msgText = wrapLink(msgText);
                } else if (userId == ROBOT_ID.RLTEXTBOT) {
                    msgText = messageHtml.RLTEXTBOT(content, flag);
                } else if (userId == ROBOT_ID.TEXTBOT) {
                    msgText = messageHtml.TEXTBOT(content, flag);
                } else if (userId == ROBOT_ID.COMMUNICATIONSBOT) {
                    msgText = messageHtml.COMMUNICATIONSBOT(content, flag);
                } else if (userId == ROBOT_ID.DZBOT) {
                    msgText = messageHtml.DZBOT(content, flag);
                } else if (userId == ROBOT_ID.BAIDUBOT) {
                    msgText = messageHtml.BAIDUBOT(content, flag);
                } else if (userId == ROBOT_ID.IWENCAIBOT) {
                    msgText = messageHtml.WENCAIBOT(content, flag);
                } else {
                    msgText = content;
                }
                if (userId != ROBOT_ID.XIAOIBOT &&
                    userId != ROBOT_ID.ECHATBOT &&
                    userId != ROBOT_ID.IFLYTEKBOT &&
                    userId != ROBOT_ID.EMOTIBOT &&
                    userId != ROBOT_ID.TEXTBOT &&
                    userId != ROBOT_ID.YANXIBOT) {
                    msgText = wrapURL(msgText);
                }
            } catch (e) {
                msgText = content;
                console.log(e);
            }
            if ('uniqlo' != robotVersion && userId != ROBOT_ID.YANXIBOT && userId != ROBOT_ID.TEXTBOT) {
                if (typeof msgText == 'string')
                    msgText = wrapClickMessage(msgText);
            }

            hiddenTransferHtml();
            if (compressionImage) {
                var container = $("<div>").append(msgText);
                container.find("img").each(function (i, img) {
                    $(img).addClass('robot-img').css("max-width", "300px");
                });
                msgText = container.html();
            }
            return msgText;
        },

        hasRobot: function () {
            return hasRobot;
        },

        isRobot: function (userId) {
            return userId.includes('BOT');
        },

        notAllowShowRate: function (userId) {
            if (!userId) {
                return !allowRateForClientCloseSession;
            } else {
                if (this.isRobot(userId)) {
                    return !allowRateForClientCloseSession;
                }
            }

            return false;
        },

        setMaxHisMessageId: function (messageId) {
            maxHisMessageId = messageId;
        },

        getRobotText: function (text, userId, flag, messageId, feedBackResult) {
            feedBackResult = feedBackResult || '';
            if (userId) {
                if ($ROBOT.isRobot(userId)) {
                    var isNews = false;
                    // var text = {
                    //     "robotType": "hr",
                    //     "similarity": 1,
                    //     "buttonList": [],
                    //     "moduleId": "core",
                    //     "type": 1,
                    //     "nodeId": "001611110779233019900017fa0316bb",
                    //     "commands": [{
                    //         "args": ["HR:213"],
                    //         "name": "route",
                    //         "state": 0
                    //     }, {"args": ["见习", "期间", "什么时候", "开始"], "argNames": [], "name": "ai_segments", "state": 0}],
                    //     "content": "当月25日前通过审核，则下月开始进入实习补助期。比如12月25日前申请通过，则1月1日起进入实习补助期间。\r\n\r\n<b>以上答案是否解决了您的问题？<\/b>[link post=\"faqvote:001611110779233019900017fa0316bb 1 vPvPsMbavOTKssO0yrG68r+qyryjvw== vPvPsMbavOTKssO0yrG68r+qyryjvw== tbHUwjI1yNXHsM2ouf3J87rLo6zU8s/C1MK/qsq8vfjI68q1z7Cyudb6xtqho7HIyOcxMtTCMjXI1cewyerH682ouf2jrNTyMdTCMcjVxvC9+MjryrXPsLK51vrG2rzkoaM= {4}\"]解决[/link] [link post=\"faqvote:001611110779233019900017fa0316bb 2 vPvPsMbavOTKssO0yrG68r+qyryjvw== vPvPsMbavOTKssO0yrG68r+qyryjvw== tbHUwjI1yNXHsM2ouf3J87rLo6zU8s/C1MK/qsq8vfjI68q1z7Cyudb6xtqho7HIyOcxMtTCMjXI1cewyerH682ouf2jrNTyMdTCMcjVxvC9+MjryrXPsLK51vrG2rzkoaM= {4}\"]未解决[/link]",
                    //     "callbackParamType": 0,
                    //     "props": {
                    //         "sentiment": "0.00",
                    //         "sessionId": "3a5f1940b8a54c3bb2c8d85b03a746f4",
                    //         "categoryId": "c54907f9cd4f4b82959e9ac8dfd3f3e4",
                    //         "objectId": "001611110779230019890017fa0316bb"
                    //     },
                    //     "relatedQuestions": []
                    // };
                    // var text = {"robotName":"hr","similarity":1,"buttonList":[{
                    //         "question": "重复付款怎么办",
                    //         "name": "人事部门",
                    //         "type": "hr",
                    //         "userId": "hexin1"
                    //     }],"moduleId":"core","type":101,"nodeId":"001607334319699013260050569b69ba","commands":[{"args":["重复","付款","怎么办"],"argNames":[],"name":"ai_segments","state":0}],"content":{"acs":"ZGD","etype":"总部or门店","path":"分类"},"callbackParamType":0,"props":{"sentiment":"0.00","sessionId":"42c9bb360777423b92aadfe7be1f6505","categoryId":"27c4737a73fa4b7095c6b50107acdb5f","objectId":"001607334319697013230050569b69ba"},"relatedQuestions":["重复付款怎么办"]};

                    // var text = {
                    //     "content": "宝宝，我来了！请详细描述你要求助的问题，让我更好的帮助你哦！\n您是否遇到以下问题：\n[1] 配送时间\n[2] 怎么还没送到\n[3] 没收到货就显示签收了",
                    //     "hint": "宝宝，我来了！请详细描述你要求助的问题，让我更好的帮助你哦！\n您是否遇到以下问题：",
                    //     "mediaId": "SgmrqLefbIR8vLnS6CL",
                    //     "msgType": "robotSimilarMatch",
                    //     "suggestions": [{
                    //         "knowledgeType": 1,
                    //         "question": "配送时间"
                    //     }, {
                    //         "knowledgeType": 1,
                    //         "question": "怎么还没送到"
                    //     }, {
                    //         "knowledgeType": 1,
                    //         "question": "没收到货就显示签收了"
                    //     }],
                    //     "userId": "13666150888",
                    //     "userType": 1,
                    //     "visitorId": "webvip13666150888"
                    // }
                    var text = $ROBOT.dealData(text, userId, flag, messageId, feedBackResult);
                    if (typeof text == "object") {
                        if (!$.isArray(text)) {
                            text = text.html;
                        }
                    }
                } else {
                    if (typeof text == 'string') {
                        if (text.startWith('faqvote:')) {
                            text = i18n.robot.faqvote;
                        }
                    }
                    text = $ROBOT.parseFormattedMsg(text);
                }
            }

            return text;
        },

        wanUrl: function () {
            if (robotEngineConfig) {
                return robotEngineConfig.wanUrl || '';
            } else {
                return '';
            }
        },

        robotOrderObj: {}, //序列号和关键字对应的key value 值

        orderNumToKey: function (num) {
            if ('uniqlo' == robotVersion && isWework) return num;
            var rs = num;
            $.each($ROBOT.robotOrderObj, function (key, value) {
                if (num == key) {
                    rs = value;
                }
            });
            return rs;
        },
        /**
         * 解析格式化的消息
         *
         * [MessageFormat data-type="robot" data-key="BOT002"]{"commands":[{"argNames":[],"args":["胃炎","胃炎","https://uat.aia.com.cn/robot/attachments/20180807114344698"],"name":"imgmsg","state":1}],"content":"","relatedQuestions":["胃炎","核保各类疾病问卷"],"similarity":1,"type":1}[/MessageFormat]
         * [MessageFormat data-type="robot" data-key="BOT002"]{"commands":[{"argNames":[],"args":["https://uat.aia.com.cn/robot/imgmsgData/62de483500994627ae97f7ade3af4d0a/articles.xml","1","UTF-8","&lt;![CDATA[&lt;Articles&gt;&lt;item&gt;&lt;Title&gt;&lt;![CDATA[龙腾出行介绍]]&gt;&lt;/Title&gt;&lt;Description&gt;&lt;![CDATA[]]&gt;&lt;/Description&gt;&lt;PicUrl&gt;&lt;![CDATA[https://uat.aia.com.cn/robot/imgmsgData/62de483500994627ae97f7ade3af4d0a/imgmsgItem1.png?t=1525418670697]]&gt;&lt;/PicUrl&gt;&lt;Url&gt;&lt;![CDATA[https://uat.aia.com.cn/robot/imgmsgData/62de483500994627ae97f7ade3af4d0a/index_1.html?t=1525418676026]]&gt;&lt;/Url&gt;&lt;/item&gt;&lt;/Articles&gt;]]&gt;"],"name":"imgtxtmsg","state":1}],"content":"","relatedQuestions":["VIP机场贵宾室","龙腾出行如何使用"],"similarity":1,"type":1}[/MessageFormat]
         */
        parseFormattedMsg: function (formattedMsg, mesageStyleClass) {
            var resultMsg = formattedMsg;
            try {
                var regexp = /^\[MessageFormat([^\]]*)\]([\s\S]*)\[\/MessageFormat\]$/;
                var ret = regexp.exec(formattedMsg);
                if (ret && ret.length === 3) {
                    var props = ret[1],
                        msgContent = ret[2],
                        pos, propsMap = {};
                    props = props.trim().replace(/\s+/g, ' ').split(' ');

                    props.forEach(function (p) {
                        if ((pos = p.indexOf('=')) > 0) {
                            var key = p.substring(0, pos);
                            var value = p.substring(pos + 1).trim();
                            value = value.replace(/"/g, '');
                            propsMap[key] = value;
                        } else {
                            propsMap[p] = true;
                        }
                    });

                    var dataType = propsMap['data-type'];
                    if (dataType === 'robot') {
                        var robotId = propsMap['data-key'];
                        msgContent = $ROBOT.parseHtmlEntity(msgContent);
                        resultMsg = $ROBOT.dealData(msgContent, robotId, true);
                    }
                    //[MessageFormat data-type="imgText" data-key="1919"]{"content": "一行描述", "title": "我是图文消息", "imageUri": "https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1571376219&di=009e86e2bdde37da9daec4f59926b18e&src=http://is4.mzstatic.com/image/pf/us/r30/Purple7/v4/f2/73/0c/f2730c1a-e58f-084a-191a-90e3586f024a/mzl.lngjyatg.png", "url": "http://www.baidu.com"}[/MessageFormat]
                    else if ('imgText' == dataType) {
                        var msgContentJSON = JSON.parse(msgContent);
                        var content = msgContentJSON.content; //需要显示的来源
                        var title = msgContentJSON.title; //需要显示的来源
                        var imageUri = msgContentJSON.imageUri; //需要显示的来源
                        var url = msgContentJSON.url; //需要显示的来源
                        resultMsg = domImageText.domImageTextHomeAppend();
                        resultMsg += domImageText.domImageText(title, content, imageUri, url, true);
                        resultMsg += domImageText.domImageTextEndAppend();
                        resultMsg = '<div class="message-imgtext" data-url="' + url + '">' +
                            '<div class="title">' + title + '</div>' +
                            '<div class="content">' +
                            '<div class="desc">' +
                            '<div class="wrapper">' + content + '</div>' +
                            '</div>' +
                            '<img class="thumb" src="' + imageUri + '">' +
                            '</div>' +
                            '</div>';
                    }
                    //[MessageFormat data-type="card" data-key="1919"]{"from": "来源天猫", "title": "我是卡片消息", "imageUri": "https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1571376219&di=009e86e2bdde37da9daec4f59926b18e&src=http://is4.mzstatic.com/image/pf/us/r30/Purple7/v4/f2/73/0c/f2730c1a-e58f-084a-191a-90e3586f024a/mzl.lngjyatg.png", "url": "http://www.baidu.com", "price": "12.00"}[/MessageFormat]
                    else if ('card' == dataType) {
                        var msgContentJSON = JSON.parse(msgContent);
                        var from = msgContentJSON.from; //需要显示的来源
                        var title = msgContentJSON.title; //需要显示的标题
                        var imageUri = msgContentJSON.imageUri; //显示的图片地址
                        var url = msgContentJSON.url; //点击之后跳转的地址
                        var price = msgContentJSON.price; //需要显示的价格
                        resultMsg = '<div class="message-card" data-url="' + url + '">' +
                            '<div class="card-image"><img class="thumb" src="' + imageUri + '"></div>' +
                            '<div class="card-content">' +
                            '<p class="card-price">' + price + '</p>' +
                            '<p class="card-title">' + title + '</p>' +
                            '<p class="card-from">' + from + '</p>' +
                            '</div>' +
                            '</div>'
                    }

                    //[MessageFormat data-type="orders" data-key="1919"][{"content":"一行描述","title":"我是图文消息","imageUri":"https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1571376219&di=009e86e2bdde37da9daec4f59926b18e&src=http://is4.mzstatic.com/image/pf/us/r30/Purple7/v4/f2/73/0c/f2730c1a-e58f-084a-191a-90e3586f024a/mzl.lngjyatg.png","orderId": "订单号123456","orderStatus": "订单状态","size": "XXXXL", "color": "太空灰", "price": "￥2000", "url":"http://www.baidu.com"},{"content":"一行描述","title":"我是图文消息","imageUri":"https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1571376219&di=009e86e2bdde37da9daec4f59926b18e&src=http://is4.mzstatic.com/image/pf/us/r30/Purple7/v4/f2/73/0c/f2730c1a-e58f-084a-191a-90e3586f024a/mzl.lngjyatg.png","orderId": "订单号123456","orderStatus": "订单状态","size": "XXXXL", "color": "太空灰", "price": "￥2000", "url":"http://www.baidu.com"}, {"content":"一行描述","title":"我是图文消息","imageUri":"https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1571376219&di=009e86e2bdde37da9daec4f59926b18e&src=http://is4.mzstatic.com/image/pf/us/r30/Purple7/v4/f2/73/0c/f2730c1a-e58f-084a-191a-90e3586f024a/mzl.lngjyatg.png","orderId": "订单号123456","orderStatus": "订单状态","size": "XXXXL", "color": "太空灰", "price": "￥2000", "url":"http://www.baidu.com"}][/MessageFormat]
                    else if ('orders' == dataType) {
                        var msgContentArr = JSON.parse(msgContent);
                        var from = propsMap['data-from'] || '';
                        var keyFrom = propsMap['data-key'] || '';
                        var title = propsMap['data-title'] || '';
                        if (msgContentArr.length > 0) {
                            var pageCount = msgContentArr.length,
                                pageSize = Math.ceil(pageCount / ordersPageSize);
                            resultMsg = "", orderIdPrev = "";
                            if (title)
                                resultMsg += '<div class="orders-title"><div>' + title + '</div></div>';
                            $.each(msgContentArr, function (i, msgContentJSON) {
                                var content = msgContentJSON.content ? msgContentJSON.content : ""; //需要显示的来源
                                var orderId = msgContentJSON.orderId ? msgContentJSON.orderId : ""; //需要显示的来源
                                var key = msgContentJSON.key ? msgContentJSON.key : ""; //需要显示的来源
                                var orderStatus = msgContentJSON.orderStatus ? msgContentJSON.orderStatus : ""; //需要显示的来源
                                var size = msgContentJSON.size ? msgContentJSON.size : ""; //尺寸
                                var quantity = msgContentJSON.quantity ? msgContentJSON.quantity : ""; //件数
                                var color = msgContentJSON.color ? msgContentJSON.color : ""; //尺寸
                                var price = msgContentJSON.price ? msgContentJSON.price : ""; //尺寸
                                var title = msgContentJSON.title ? msgContentJSON.title : ""; //需要显示的来源
                                var imageUri = msgContentJSON.imageUri ? msgContentJSON.imageUri : ""; //需要显示的来源
                                var url = msgContentJSON.url ? msgContentJSON.url : ""; //需要显示的来源
                                var funca = msgContentJSON.funca ? msgContentJSON.funca : ""; //需要显示的来源
                                var funci = msgContentJSON.funci ? msgContentJSON.funci : ""; //需要显示的来源
                                var send = msgContentJSON.send ? msgContentJSON.send : ""; //需要显示的来源
                                var noReasonFlag = msgContentJSON.noReasonFlag ? msgContentJSON.noReasonFlag : ""; //需要显示的来源
                                var hideClass = ordersPageSize > i ? '' : 'hidden';
                                resultMsg += '<div class="message-orders ' + hideClass + '" data-index="' + parseInt(i / ordersPageSize) + '" data-url="' + url + '" data-funca="' + funca + '" data-funci="' + funci + '" data-send="' + send + '" data-keyfrom="' + keyFrom + '" data-from="' + from + '" data-key="' + key + '">';
                                if (i % ordersPageSize) {
                                    orderIdPrev = '';
                                }
                                if (orderId && orderId != orderIdPrev) {
                                    resultMsg += '<div class="order-head">' +
                                        '<div class="order-id">' + orderId + '</div>' +
                                        '<div class="order-status">' + orderStatus + '</div>' +
                                        '</div>';
                                }
                                orderIdPrev = orderId;

                                resultMsg += '<div class="order-container">' +
                                    '<div class="orders-left">' +
                                    '<img class="thumb" src="' + imageUri + '">' +
                                    '</div>' +
                                    '<div class="orders-right">' +
                                    '<div class="order-title">' + title + '</div>' +
                                    '<div class="order-content">';
                                if (size)
                                    resultMsg += '<div class="order-size">尺寸：' + size + '</div>';
                                if (color)
                                    resultMsg += '<div class="order-color">颜色：' + color + '</div>';
                                // if (content)
                                //     resultMsg += '<div class="order-wrapper">' + content + '</div>';
                                if (noReasonFlag) {
                                    noReasonFlag = (noReasonFlag == 'Y') ? i18n.robot.orders.noReasonFlagY : i18n.robot.orders.noReasonFlagN;
                                    resultMsg += '<div class="order-wrapper">' + noReasonFlag + '</div>';
                                }
                                if (price)
                                    resultMsg += '<div class="order-price">￥ ' + price + '</div>';
                                if (quantity)
                                    resultMsg += '<div class="order-color">x' + quantity + '</div>';
                                resultMsg += '</div>' +
                                    '</div>' +
                                    '</div>' +
                                    '</div>';
                            });

                            if (pageCount > ordersPageSize) {
                                resultMsg += '<div class="order-footer" data-page="0" data-size="' + pageSize + '">' +
                                    ' <span class="next orders-button" data-type="next">' + i18n.robot.orders.buttonNext + '</span>' +
                                    ' <span class="prev orders-button" data-type="prev">' + i18n.robot.orders.buttonPrev + '</span>' +
                                    '</div>';
                            }
                        }

                    }
                } else {
                    resultMsg = wrapURL(formattedMsg);
                }
            } catch (e) {
                robotLog(e.message, 'on parseFormattedMsg');
            }
            return resultMsg;
        },

        getContentMaxHeight: function () {
            return contentMaxHeight;
        },

        parseHtmlEntity: function (msg) {
            if (msg) {
                msg = msg.replace(/&lt;/g, "<").replace(/&gt;/g, ">");
            }
            return msg;
        },

        transferChat: function (queue, transferInfo) {
            console.log("Call Transfer And Info : " + transferInfo)
            //如果当前转人工状态是true 不执行转人工
            if (_transfering) return;
            $ROBOT.transferingChange(true);
            robotLog(_transfering, '_transfering');
            Constants.robot.isRobot = false;
            if ($config.queue.permFlag == '1') {
                createPrivateChat(queue);
            } else {
                if (mobileVerify && $config.client.clientType == 1 && $MVF) {
                    $MVF.show({
                        "success": function (mobile) {
                            var robotId = ROBOT_FROM_TYPE[robotEngineConfig.type];
                            transferInfo = transferInfo ? encodeURIComponent(transferInfo) : '';
                            if ($config.mobile) {
                                robotTransferToQueue(robotId, queue, transferInfo);
                            } else {
                                $F.robotTransferToQueue(robotId, queue, transferInfo);
                            }
                        },
                        'error': function () {
                            _transfering = false;
                        },
                        path: mobileVerifyPath
                    })
                } else {
                    var robotId = ROBOT_FROM_TYPE[robotEngineConfig.type];
                    transferInfo = transferInfo ? encodeURIComponent(transferInfo) : '';
                    if ($config.mobile) {
                        robotTransferToQueue(robotId, queue, transferInfo)
                    } else {
                        $F.robotTransferToQueue(robotId, queue, transferInfo);
                    }
                }
            }
        },
        transferDialog: function (message, confirmFunc, cancelFunc) {
            if ($config.mobile) {
                setTimeout(function () {
                    layer.open({
                        content: i18n.page.transferTip,
                        className: 'confirm-mobile',
                        btn: [i18n.page.dialog.yes, i18n.page.dialog.cancel],
                        yes: function (index) {
                            if ($.isFunction(confirmFunc)) {
                                confirmFunc();
                            }
                            layer.close(index)
                        },
                        no: function (index) {
                            if ($.isFunction(cancelFunc)) {
                                cancelFunc();
                            }
                            layer.close(index)
                        }
                    });
                }, 1000)
            } else {
                $F.showConfirm(message || i18n.page.transferTip, function () {
                    if ($.isFunction(confirmFunc)) {
                        confirmFunc();
                    }
                    UI.cuestomerService();
                }, cancelFunc)
            }
        },
        canSendMessage: function () {
            if ($CITY && $CITY.canSendMessage && $CITY.canSendMessage()) {
                return true
            } else {
                return false
            }
        }
    }
})
(jQuery);